DATACMNS-867 - First draft.
This commit is contained in:
6
src/test/java/org/springframework/data/annotation/TypeAliasUnitTests.java
Normal file → Executable file
6
src/test/java/org/springframework/data/annotation/TypeAliasUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.annotation;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@@ -37,8 +36,7 @@ public class TypeAliasUnitTests {
|
||||
AnnotatedTypeScanner scanner = new AnnotatedTypeScanner(Persistent.class);
|
||||
Set<Class<?>> types = scanner.findTypes(getClass().getPackage().getName());
|
||||
|
||||
assertThat(types, hasSize(2));
|
||||
assertThat(types, hasItems(SampleType.class, TypeAlias.class));
|
||||
assertThat(types).containsExactlyInAnyOrder(SampleType.class, TypeAlias.class);
|
||||
}
|
||||
|
||||
@TypeAlias(value = "foo")
|
||||
|
||||
32
src/test/java/org/springframework/data/auditing/AnnotationAuditingMetadataUnitTests.java
Normal file → Executable file
32
src/test/java/org/springframework/data/auditing/AnnotationAuditingMetadataUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.auditing;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
@@ -40,50 +39,47 @@ public class AnnotationAuditingMetadataUnitTests {
|
||||
static final Field lastModifiedByField = ReflectionUtils.findField(AnnotatedUser.class, "lastModifiedBy");
|
||||
static final Field lastModifiedDateField = ReflectionUtils.findField(AnnotatedUser.class, "lastModifiedDate");
|
||||
|
||||
@Rule
|
||||
public ExpectedException exception = ExpectedException.none();
|
||||
@Rule public ExpectedException exception = ExpectedException.none();
|
||||
|
||||
@Test
|
||||
public void checkAnnotationDiscovery() {
|
||||
|
||||
AnnotationAuditingMetadata metadata = AnnotationAuditingMetadata.getMetadata(AnnotatedUser.class);
|
||||
assertThat(metadata, is(notNullValue()));
|
||||
|
||||
assertThat(createdByField, is(metadata.getCreatedByField()));
|
||||
assertThat(createdDateField, is(metadata.getCreatedDateField()));
|
||||
assertThat(lastModifiedByField, is(metadata.getLastModifiedByField()));
|
||||
assertThat(lastModifiedDateField, is(metadata.getLastModifiedDateField()));
|
||||
assertThat(metadata).isNotNull();
|
||||
assertThat(metadata.getCreatedByField()).hasValue(createdByField);
|
||||
assertThat(metadata.getCreatedDateField()).hasValue(createdDateField);
|
||||
assertThat(metadata.getLastModifiedByField()).hasValue(lastModifiedByField);
|
||||
assertThat(metadata.getLastModifiedDateField()).hasValue(lastModifiedDateField);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkCaching() {
|
||||
|
||||
AnnotationAuditingMetadata firstCall = AnnotationAuditingMetadata.getMetadata(AnnotatedUser.class);
|
||||
assertThat(firstCall, is(notNullValue()));
|
||||
assertThat(firstCall).isNotNull();
|
||||
|
||||
AnnotationAuditingMetadata secondCall = AnnotationAuditingMetadata.getMetadata(AnnotatedUser.class);
|
||||
assertThat(firstCall, is(secondCall));
|
||||
assertThat(firstCall).isEqualTo(secondCall);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkIsAuditable() {
|
||||
|
||||
AnnotationAuditingMetadata metadata = AnnotationAuditingMetadata.getMetadata(AnnotatedUser.class);
|
||||
assertThat(metadata, is(notNullValue()));
|
||||
;
|
||||
assertThat(metadata.isAuditable(), is(true));
|
||||
assertThat(metadata).isNotNull();
|
||||
assertThat(metadata.isAuditable()).isTrue();
|
||||
|
||||
metadata = AnnotationAuditingMetadata.getMetadata(NonAuditableUser.class);
|
||||
assertThat(metadata, is(notNullValue()));
|
||||
assertThat(metadata.isAuditable(), is(false));
|
||||
assertThat(metadata).isNotNull();
|
||||
assertThat(metadata.isAuditable()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsInvalidDateTypeField() {
|
||||
|
||||
class Sample {
|
||||
@CreatedDate
|
||||
String field;
|
||||
@CreatedDate String field;
|
||||
}
|
||||
|
||||
exception.expect(IllegalStateException.class);
|
||||
|
||||
@@ -15,7 +15,9 @@
|
||||
*/
|
||||
package org.springframework.data.auditing;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.domain.Auditable;
|
||||
|
||||
/**
|
||||
@@ -24,15 +26,15 @@ import org.springframework.data.domain.Auditable;
|
||||
* @author Oliver Gierke
|
||||
* @since 1.5
|
||||
*/
|
||||
class AuditedUser implements Auditable<AuditedUser, Long> {
|
||||
class AuditedUser implements Auditable<AuditedUser, Long, LocalDateTime> {
|
||||
|
||||
private static final long serialVersionUID = -840865084027597951L;
|
||||
|
||||
Long id;
|
||||
AuditedUser createdBy;
|
||||
AuditedUser modifiedBy;
|
||||
DateTime createdDate;
|
||||
DateTime modifiedDate;
|
||||
LocalDateTime createdDate;
|
||||
LocalDateTime modifiedDate;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
@@ -42,35 +44,35 @@ class AuditedUser implements Auditable<AuditedUser, Long> {
|
||||
return id == null;
|
||||
}
|
||||
|
||||
public AuditedUser getCreatedBy() {
|
||||
return createdBy;
|
||||
public Optional<AuditedUser> getCreatedBy() {
|
||||
return Optional.ofNullable(createdBy);
|
||||
}
|
||||
|
||||
public void setCreatedBy(AuditedUser createdBy) {
|
||||
this.createdBy = createdBy;
|
||||
public void setCreatedBy(Optional<? extends AuditedUser> createdBy) {
|
||||
this.createdBy = createdBy.orElse(null);
|
||||
}
|
||||
|
||||
public DateTime getCreatedDate() {
|
||||
return createdDate;
|
||||
public Optional<LocalDateTime> getCreatedDate() {
|
||||
return Optional.ofNullable(createdDate);
|
||||
}
|
||||
|
||||
public void setCreatedDate(DateTime creationDate) {
|
||||
this.createdDate = creationDate;
|
||||
public void setCreatedDate(Optional<? extends LocalDateTime> creationDate) {
|
||||
this.createdDate = creationDate.orElse(null);
|
||||
}
|
||||
|
||||
public AuditedUser getLastModifiedBy() {
|
||||
return modifiedBy;
|
||||
public Optional<AuditedUser> getLastModifiedBy() {
|
||||
return Optional.ofNullable(modifiedBy);
|
||||
}
|
||||
|
||||
public void setLastModifiedBy(AuditedUser lastModifiedBy) {
|
||||
this.modifiedBy = lastModifiedBy;
|
||||
public void setLastModifiedBy(Optional<? extends AuditedUser> lastModifiedBy) {
|
||||
this.modifiedBy = lastModifiedBy.orElse(null);
|
||||
}
|
||||
|
||||
public DateTime getLastModifiedDate() {
|
||||
return modifiedDate;
|
||||
public Optional<LocalDateTime> getLastModifiedDate() {
|
||||
return Optional.ofNullable(modifiedDate);
|
||||
}
|
||||
|
||||
public void setLastModifiedDate(DateTime lastModifiedDate) {
|
||||
this.modifiedDate = lastModifiedDate;
|
||||
public void setLastModifiedDate(Optional<? extends LocalDateTime> lastModifiedDate) {
|
||||
this.modifiedDate = lastModifiedDate.orElse(null);
|
||||
}
|
||||
}
|
||||
|
||||
72
src/test/java/org/springframework/data/auditing/AuditingHandlerUnitTests.java
Normal file → Executable file
72
src/test/java/org/springframework/data/auditing/AuditingHandlerUnitTests.java
Normal file → Executable file
@@ -15,15 +15,15 @@
|
||||
*/
|
||||
package org.springframework.data.auditing;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.AuditorAware;
|
||||
import org.springframework.data.mapping.context.MappingContext;
|
||||
import org.springframework.data.mapping.context.PersistentEntities;
|
||||
|
||||
/**
|
||||
@@ -38,20 +38,20 @@ public class AuditingHandlerUnitTests {
|
||||
AuditingHandler handler;
|
||||
AuditorAware<AuditedUser> auditorAware;
|
||||
|
||||
AuditedUser user;
|
||||
Optional<AuditedUser> user;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
handler = getHandler();
|
||||
user = new AuditedUser();
|
||||
user = Optional.of(new AuditedUser());
|
||||
|
||||
auditorAware = mock(AuditorAware.class);
|
||||
when(auditorAware.getCurrentAuditor()).thenReturn(user);
|
||||
}
|
||||
|
||||
protected AuditingHandler getHandler() {
|
||||
return new AuditingHandler(new PersistentEntities(Collections.<MappingContext<?, ?>> emptySet()));
|
||||
return new AuditingHandler(new PersistentEntities(Collections.emptySet()));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -62,11 +62,14 @@ public class AuditingHandlerUnitTests {
|
||||
|
||||
handler.markCreated(user);
|
||||
|
||||
assertNotNull(user.getCreatedDate());
|
||||
assertNotNull(user.getLastModifiedDate());
|
||||
assertThat(user).hasValueSatisfying(it -> {
|
||||
|
||||
assertNull(user.getCreatedBy());
|
||||
assertNull(user.getLastModifiedBy());
|
||||
assertThat(it.getCreatedDate()).isPresent();
|
||||
assertThat(it.getLastModifiedDate()).isPresent();
|
||||
|
||||
assertThat(it.getCreatedBy()).isNotPresent();
|
||||
assertThat(it.getLastModifiedBy()).isNotPresent();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -79,11 +82,14 @@ public class AuditingHandlerUnitTests {
|
||||
|
||||
handler.markCreated(user);
|
||||
|
||||
assertNotNull(user.getCreatedDate());
|
||||
assertNotNull(user.getLastModifiedDate());
|
||||
assertThat(user).hasValueSatisfying(it -> {
|
||||
|
||||
assertNotNull(user.getCreatedBy());
|
||||
assertNotNull(user.getLastModifiedBy());
|
||||
assertThat(it.getCreatedDate()).isPresent();
|
||||
assertThat(it.getLastModifiedDate()).isPresent();
|
||||
|
||||
assertThat(it.getCreatedBy()).isPresent();
|
||||
assertThat(it.getLastModifiedBy()).isPresent();
|
||||
});
|
||||
|
||||
verify(auditorAware).getCurrentAuditor();
|
||||
}
|
||||
@@ -98,11 +104,14 @@ public class AuditingHandlerUnitTests {
|
||||
handler.setModifyOnCreation(false);
|
||||
handler.markCreated(user);
|
||||
|
||||
assertNotNull(user.getCreatedDate());
|
||||
assertNotNull(user.getCreatedBy());
|
||||
assertThat(user).hasValueSatisfying(it -> {
|
||||
|
||||
assertNull(user.getLastModifiedBy());
|
||||
assertNull(user.getLastModifiedDate());
|
||||
assertThat(it.getCreatedDate()).isPresent();
|
||||
assertThat(it.getCreatedBy()).isPresent();
|
||||
|
||||
assertThat(it.getLastModifiedBy()).isNotPresent();
|
||||
assertThat(it.getLastModifiedDate()).isNotPresent();
|
||||
});
|
||||
|
||||
verify(auditorAware).getCurrentAuditor();
|
||||
}
|
||||
@@ -113,17 +122,22 @@ public class AuditingHandlerUnitTests {
|
||||
@Test
|
||||
public void onlySetsModificationDataOnNotNewEntities() {
|
||||
|
||||
user = new AuditedUser();
|
||||
user.id = 1L;
|
||||
AuditedUser audited = new AuditedUser();
|
||||
audited.id = 1L;
|
||||
|
||||
user = Optional.of(audited);
|
||||
|
||||
handler.setAuditorAware(auditorAware);
|
||||
handler.markModified(user);
|
||||
|
||||
assertNull(user.getCreatedBy());
|
||||
assertNull(user.getCreatedDate());
|
||||
assertThat(user).hasValueSatisfying(it -> {
|
||||
|
||||
assertNotNull(user.getLastModifiedBy());
|
||||
assertNotNull(user.getLastModifiedDate());
|
||||
assertThat(it.getCreatedBy()).isNotPresent();
|
||||
assertThat(it.getCreatedDate()).isNotPresent();
|
||||
|
||||
assertThat(it.getLastModifiedBy()).isPresent();
|
||||
assertThat(it.getLastModifiedDate()).isPresent();
|
||||
});
|
||||
|
||||
verify(auditorAware).getCurrentAuditor();
|
||||
}
|
||||
@@ -135,17 +149,21 @@ public class AuditingHandlerUnitTests {
|
||||
handler.setAuditorAware(auditorAware);
|
||||
handler.markCreated(user);
|
||||
|
||||
assertNotNull(user.getCreatedBy());
|
||||
assertNull(user.getCreatedDate());
|
||||
assertThat(user).hasValueSatisfying(it -> {
|
||||
|
||||
assertNotNull(user.getLastModifiedBy());
|
||||
assertNull(user.getLastModifiedDate());
|
||||
assertThat(it.getCreatedBy()).isPresent();
|
||||
assertThat(it.getCreatedDate()).isNotPresent();
|
||||
|
||||
assertThat(it.getLastModifiedBy()).isPresent();
|
||||
assertThat(it.getLastModifiedDate()).isNotPresent();
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATAJPA-9
|
||||
public void usesDateTimeProviderIfConfigured() {
|
||||
|
||||
DateTimeProvider provider = mock(DateTimeProvider.class);
|
||||
doReturn(Optional.empty()).when(provider).getNow();
|
||||
|
||||
handler.setDateTimeProvider(provider);
|
||||
handler.markCreated(user);
|
||||
|
||||
43
src/test/java/org/springframework/data/auditing/DefaultAuditableBeanWrapperFactoryUnitTests.java
Normal file → Executable file
43
src/test/java/org/springframework/data/auditing/DefaultAuditableBeanWrapperFactoryUnitTests.java
Normal file → Executable file
@@ -15,10 +15,10 @@
|
||||
*/
|
||||
package org.springframework.data.auditing;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.auditing.DefaultAuditableBeanWrapperFactory.AuditableInterfaceBeanWrapper;
|
||||
@@ -35,42 +35,47 @@ public class DefaultAuditableBeanWrapperFactoryUnitTests {
|
||||
DefaultAuditableBeanWrapperFactory factory = new DefaultAuditableBeanWrapperFactory();
|
||||
|
||||
@Test
|
||||
public void returnsNullForNullSource() {
|
||||
assertThat(factory.getBeanWrapperFor(null), is(nullValue()));
|
||||
public void returnsEmptyForEmptySource() {
|
||||
assertThat(factory.getBeanWrapperFor(Optional.empty())).isNotPresent();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsAuditableInterfaceBeanWrapperForAuditable() {
|
||||
|
||||
AuditableBeanWrapper wrapper = factory.getBeanWrapperFor(new AuditedUser());
|
||||
assertThat(wrapper, is(instanceOf(AuditableInterfaceBeanWrapper.class)));
|
||||
assertThat(factory.getBeanWrapperFor(Optional.of(new AuditedUser()))).hasValueSatisfying(it -> {
|
||||
assertThat(it).isInstanceOf(AuditableInterfaceBeanWrapper.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsReflectionAuditingBeanWrapperForNonAuditableButAnnotated() {
|
||||
|
||||
AuditableBeanWrapper wrapper = factory.getBeanWrapperFor(new AnnotatedUser());
|
||||
assertThat(wrapper, is(instanceOf(ReflectionAuditingBeanWrapper.class)));
|
||||
assertThat(factory.getBeanWrapperFor(Optional.of(new AnnotatedUser()))).hasValueSatisfying(it -> {
|
||||
assertThat(it).isInstanceOf(ReflectionAuditingBeanWrapper.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsNullForNonAuditableType() {
|
||||
|
||||
AuditableBeanWrapper wrapper = factory.getBeanWrapperFor(new Object());
|
||||
assertThat(wrapper, is(nullValue()));
|
||||
public void returnsEmptyForNonAuditableType() {
|
||||
assertThat(factory.getBeanWrapperFor(Optional.of(new Object()))).isNotPresent();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-643
|
||||
public void setsJsr310AndThreeTenBpTypes() {
|
||||
|
||||
Jsr310ThreeTenBpAuditedUser user = new Jsr310ThreeTenBpAuditedUser();
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
Instant instant = Instant.now();
|
||||
|
||||
AuditableBeanWrapper wrapper = factory.getBeanWrapperFor(user);
|
||||
wrapper.setCreatedDate(calendar);
|
||||
wrapper.setLastModifiedDate(calendar);
|
||||
Optional<AuditableBeanWrapper> wrapper = factory.getBeanWrapperFor(Optional.of(user));
|
||||
|
||||
assertThat(wrapper).hasValueSatisfying(it -> {
|
||||
|
||||
it.setCreatedDate(Optional.of(instant));
|
||||
it.setLastModifiedDate(Optional.of(instant));
|
||||
|
||||
assertThat(user.createdDate).isNotNull();
|
||||
assertThat(user.lastModifiedDate).isNotNull();
|
||||
});
|
||||
|
||||
assertThat(user.createdDate, is(notNullValue()));
|
||||
assertThat(user.lastModifiedDate, is(notNullValue()));
|
||||
}
|
||||
}
|
||||
|
||||
31
src/test/java/org/springframework/data/auditing/IsNewAwareAuditingHandlerUnitTests.java
Normal file → Executable file
31
src/test/java/org/springframework/data/auditing/IsNewAwareAuditingHandlerUnitTests.java
Normal file → Executable file
@@ -15,16 +15,17 @@
|
||||
*/
|
||||
package org.springframework.data.auditing;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.mapping.context.MappingContext;
|
||||
import org.springframework.data.mapping.context.PersistentEntities;
|
||||
@@ -55,10 +56,11 @@ public class IsNewAwareAuditingHandlerUnitTests extends AuditingHandlerUnitTests
|
||||
public void delegatesToMarkCreatedForNewEntity() {
|
||||
|
||||
AuditedUser user = new AuditedUser();
|
||||
getHandler().markAudited(user);
|
||||
|
||||
assertThat(user.createdDate, is(notNullValue()));
|
||||
assertThat(user.modifiedDate, is(notNullValue()));
|
||||
getHandler().markAudited(Optional.of(user));
|
||||
|
||||
assertThat(user.createdDate).isNotNull();
|
||||
assertThat(user.modifiedDate).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -66,10 +68,11 @@ public class IsNewAwareAuditingHandlerUnitTests extends AuditingHandlerUnitTests
|
||||
|
||||
AuditedUser user = new AuditedUser();
|
||||
user.id = 1L;
|
||||
getHandler().markAudited(user);
|
||||
|
||||
assertThat(user.createdDate, is(nullValue()));
|
||||
assertThat(user.modifiedDate, is(notNullValue()));
|
||||
getHandler().markAudited(Optional.of(user));
|
||||
|
||||
assertThat(user.createdDate).isNull();
|
||||
assertThat(user.modifiedDate).isNotNull();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class) // DATACMNS-365
|
||||
@@ -83,18 +86,18 @@ public class IsNewAwareAuditingHandlerUnitTests extends AuditingHandlerUnitTests
|
||||
}
|
||||
|
||||
@Test // DATACMNS-638
|
||||
public void handlingNullIsANoOp() {
|
||||
public void handlingOptionalIsANoOp() {
|
||||
|
||||
IsNewAwareAuditingHandler handler = getHandler();
|
||||
|
||||
handler.markAudited(null);
|
||||
handler.markCreated(null);
|
||||
handler.markModified(null);
|
||||
handler.markAudited(Optional.empty());
|
||||
handler.markCreated(Optional.empty());
|
||||
handler.markModified(Optional.empty());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-957
|
||||
public void skipsEntityWithoutIdentifier() {
|
||||
getHandler().markAudited(new EntityWithoutId());
|
||||
getHandler().markAudited(Optional.of(new EntityWithoutId()));
|
||||
}
|
||||
|
||||
static class Domain {
|
||||
|
||||
57
src/test/java/org/springframework/data/auditing/MappingAuditableBeanWrapperFactoryUnitTests.java
Normal file → Executable file
57
src/test/java/org/springframework/data/auditing/MappingAuditableBeanWrapperFactoryUnitTests.java
Normal file → Executable file
@@ -15,18 +15,20 @@
|
||||
*/
|
||||
package org.springframework.data.auditing;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Calendar;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.annotation.CreatedBy;
|
||||
import org.springframework.data.annotation.LastModifiedBy;
|
||||
@@ -38,11 +40,12 @@ import org.springframework.data.mapping.context.PersistentEntities;
|
||||
import org.springframework.data.mapping.context.SampleMappingContext;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link MappingAuditableBeanWrapperFactory}.
|
||||
* Unit tests for {@link MappingAuditableBeanWrapperFactory}. TODO: Which date types to support?
|
||||
*
|
||||
* @author Oliver Gierke
|
||||
* @since 1.8
|
||||
*/
|
||||
@Ignore
|
||||
public class MappingAuditableBeanWrapperFactoryUnitTests {
|
||||
|
||||
DefaultAuditableBeanWrapperFactory factory;
|
||||
@@ -62,45 +65,53 @@ public class MappingAuditableBeanWrapperFactoryUnitTests {
|
||||
public void discoversAuditingPropertyOnField() {
|
||||
|
||||
Sample sample = new Sample();
|
||||
AuditableBeanWrapper wrapper = factory.getBeanWrapperFor(sample);
|
||||
|
||||
assertThat(wrapper, is(notNullValue()));
|
||||
Optional<AuditableBeanWrapper> wrapper = factory.getBeanWrapperFor(Optional.of(sample));
|
||||
|
||||
wrapper.setCreatedBy("Me!");
|
||||
assertThat(sample.createdBy, is(notNullValue()));
|
||||
assertThat(wrapper).hasValueSatisfying(it -> {
|
||||
|
||||
it.setCreatedBy(Optional.of("Me!"));
|
||||
assertThat(sample.createdBy).isNotNull();
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-365
|
||||
public void discoversAuditingPropertyOnAccessor() {
|
||||
|
||||
Sample sample = new Sample();
|
||||
AuditableBeanWrapper wrapper = factory.getBeanWrapperFor(sample);
|
||||
|
||||
assertThat(wrapper, is(notNullValue()));
|
||||
Optional<AuditableBeanWrapper> wrapper = factory.getBeanWrapperFor(Optional.of(sample));
|
||||
|
||||
wrapper.setLastModifiedBy("Me, too!");
|
||||
assertThat(sample.lastModifiedBy, is(notNullValue()));
|
||||
assertThat(wrapper).hasValueSatisfying(it -> {
|
||||
|
||||
it.setLastModifiedBy(Optional.of("Me, too!"));
|
||||
assertThat(sample.lastModifiedBy).isNotNull();
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-365
|
||||
public void settingInavailablePropertyIsNoop() {
|
||||
|
||||
Sample sample = new Sample();
|
||||
AuditableBeanWrapper wrapper = factory.getBeanWrapperFor(sample);
|
||||
|
||||
wrapper.setLastModifiedDate(new GregorianCalendar());
|
||||
Optional<AuditableBeanWrapper> wrapper = factory.getBeanWrapperFor(Optional.of(sample));
|
||||
|
||||
assertThat(wrapper).hasValueSatisfying(it -> {
|
||||
it.setLastModifiedDate(Optional.of(Instant.now()));
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-365
|
||||
public void doesNotReturnWrapperForEntityNotUsingAuditing() {
|
||||
assertThat(factory.getBeanWrapperFor(new NoAuditing()), is(nullValue()));
|
||||
assertThat(factory.getBeanWrapperFor(Optional.of(new NoAuditing()))).isNotPresent();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-365
|
||||
public void returnsAuditableWrapperForAuditable() {
|
||||
|
||||
assertThat(factory.getBeanWrapperFor(mock(ExtendingAuditable.class)),
|
||||
is(instanceOf(AuditableInterfaceBeanWrapper.class)));
|
||||
assertThat(factory.getBeanWrapperFor(Optional.of(mock(ExtendingAuditable.class)))).hasValueSatisfying(it -> {
|
||||
assertThat(it).isInstanceOf(AuditableInterfaceBeanWrapper.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-638
|
||||
@@ -148,16 +159,16 @@ public class MappingAuditableBeanWrapperFactoryUnitTests {
|
||||
.convert(reference));
|
||||
}
|
||||
|
||||
private final void assertLastModificationDate(Object source, Date expected) {
|
||||
|
||||
Calendar calendar = new GregorianCalendar();
|
||||
calendar.setTime(expected);
|
||||
private void assertLastModificationDate(Object source, Object expected) {
|
||||
|
||||
Sample sample = new Sample();
|
||||
sample.lastModifiedDate = source;
|
||||
|
||||
AuditableBeanWrapper wrapper = factory.getBeanWrapperFor(sample);
|
||||
assertThat(wrapper.getLastModifiedDate(), is(calendar));
|
||||
Optional<AuditableBeanWrapper> wrapper = factory.getBeanWrapperFor(Optional.of(sample));
|
||||
|
||||
assertThat(wrapper).hasValueSatisfying(it -> {
|
||||
assertThat(it.getLastModifiedDate()).isEqualTo(expected);
|
||||
});
|
||||
}
|
||||
|
||||
static class Sample {
|
||||
@@ -177,7 +188,7 @@ public class MappingAuditableBeanWrapperFactoryUnitTests {
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
static abstract class ExtendingAuditable implements Auditable<Object, Long> {
|
||||
static abstract class ExtendingAuditable implements Auditable<Object, Long, LocalDateTime> {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
38
src/test/java/org/springframework/data/auditing/ReflectionAuditingBeanWrapperUnitTests.java
Normal file → Executable file
38
src/test/java/org/springframework/data/auditing/ReflectionAuditingBeanWrapperUnitTests.java
Normal file → Executable file
@@ -15,11 +15,11 @@
|
||||
*/
|
||||
package org.springframework.data.auditing;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.junit.Before;
|
||||
@@ -27,6 +27,7 @@ import org.junit.Test;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.data.annotation.LastModifiedDate;
|
||||
import org.springframework.data.auditing.DefaultAuditableBeanWrapperFactory.ReflectionAuditingBeanWrapper;
|
||||
import org.springframework.data.convert.Jsr310Converters.LocalDateTimeToDateConverter;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link ReflectionAuditingBeanWrapper}.
|
||||
@@ -40,14 +41,11 @@ public class ReflectionAuditingBeanWrapperUnitTests {
|
||||
AnnotatedUser user;
|
||||
AuditableBeanWrapper wrapper;
|
||||
|
||||
Calendar calendar = new GregorianCalendar();
|
||||
DateTime time = new DateTime(calendar);
|
||||
LocalDateTime time = LocalDateTime.now();
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
assertThat(time, is(new DateTime(calendar)));
|
||||
|
||||
this.user = new AnnotatedUser();
|
||||
this.wrapper = new ReflectionAuditingBeanWrapper(user);
|
||||
}
|
||||
@@ -55,15 +53,15 @@ public class ReflectionAuditingBeanWrapperUnitTests {
|
||||
@Test
|
||||
public void setsDateTimeFieldCorrectly() {
|
||||
|
||||
wrapper.setCreatedDate(calendar);
|
||||
assertThat(user.createdDate, is(time));
|
||||
wrapper.setCreatedDate(Optional.of(time));
|
||||
assertThat(user.createdDate).isEqualTo(new DateTime(LocalDateTimeToDateConverter.INSTANCE.convert(time)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setsDateFieldCorrectly() {
|
||||
|
||||
wrapper.setLastModifiedDate(calendar);
|
||||
assertThat(user.lastModifiedDate, is(time.toDate()));
|
||||
wrapper.setLastModifiedDate(Optional.of(time));
|
||||
assertThat(user.lastModifiedDate).isEqualTo(LocalDateTimeToDateConverter.INSTANCE.convert(time));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -79,11 +77,11 @@ public class ReflectionAuditingBeanWrapperUnitTests {
|
||||
Sample sample = new Sample();
|
||||
AuditableBeanWrapper wrapper = new ReflectionAuditingBeanWrapper(sample);
|
||||
|
||||
wrapper.setCreatedDate(calendar);
|
||||
assertThat(sample.createdDate, is(time.getMillis()));
|
||||
wrapper.setCreatedDate(Optional.of(time));
|
||||
assertThat(sample.createdDate).isEqualTo(time.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli());
|
||||
|
||||
wrapper.setLastModifiedDate(calendar);
|
||||
assertThat(sample.modifiedDate, is(time.getMillis()));
|
||||
wrapper.setLastModifiedDate(Optional.of(time));
|
||||
assertThat(sample.modifiedDate).isEqualTo(time.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -91,10 +89,10 @@ public class ReflectionAuditingBeanWrapperUnitTests {
|
||||
|
||||
Object object = new Object();
|
||||
|
||||
wrapper.setCreatedBy(object);
|
||||
assertThat(user.createdBy, is(object));
|
||||
wrapper.setCreatedBy(Optional.of(object));
|
||||
assertThat(user.createdBy).isEqualTo(object);
|
||||
|
||||
wrapper.setLastModifiedBy(object);
|
||||
assertThat(user.lastModifiedBy, is(object));
|
||||
wrapper.setLastModifiedBy(Optional.of(object));
|
||||
assertThat(user.lastModifiedBy).isEqualTo(object);
|
||||
}
|
||||
}
|
||||
|
||||
0
src/test/java/org/springframework/data/auditing/config/AuditingBeanDefinitionRegistrarSupportUnitTests.java
Normal file → Executable file
0
src/test/java/org/springframework/data/auditing/config/AuditingBeanDefinitionRegistrarSupportUnitTests.java
Normal file → Executable file
43
src/test/java/org/springframework/data/authentication/UserCredentialsUnitTests.java
Normal file → Executable file
43
src/test/java/org/springframework/data/authentication/UserCredentialsUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.authentication;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -31,17 +30,17 @@ public class UserCredentialsUnitTests {
|
||||
public void treatsEmptyStringAsNull() {
|
||||
|
||||
UserCredentials credentials = new UserCredentials("", "");
|
||||
assertThat(credentials.getUsername(), is(nullValue()));
|
||||
assertThat(credentials.hasUsername(), is(false));
|
||||
assertThat(credentials.getPassword(), is(nullValue()));
|
||||
assertThat(credentials.hasPassword(), is(false));
|
||||
assertThat(credentials.getUsername()).isNull();
|
||||
assertThat(credentials.hasUsername()).isFalse();
|
||||
assertThat(credentials.getPassword()).isNull();
|
||||
assertThat(credentials.hasPassword()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-142
|
||||
public void noCredentialsNullsUsernameAndPassword() {
|
||||
|
||||
assertThat(UserCredentials.NO_CREDENTIALS.getUsername(), is(nullValue()));
|
||||
assertThat(UserCredentials.NO_CREDENTIALS.getPassword(), is(nullValue()));
|
||||
assertThat(UserCredentials.NO_CREDENTIALS.getUsername()).isNull();
|
||||
assertThat(UserCredentials.NO_CREDENTIALS.getPassword()).isNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-142
|
||||
@@ -49,10 +48,10 @@ public class UserCredentialsUnitTests {
|
||||
|
||||
UserCredentials credentials = new UserCredentials("username", null);
|
||||
|
||||
assertThat(credentials.hasUsername(), is(true));
|
||||
assertThat(credentials.getUsername(), is("username"));
|
||||
assertThat(credentials.hasPassword(), is(false));
|
||||
assertThat(credentials.getPassword(), is(nullValue()));
|
||||
assertThat(credentials.hasUsername()).isTrue();
|
||||
assertThat(credentials.getUsername()).isEqualTo("username");
|
||||
assertThat(credentials.hasPassword()).isFalse();
|
||||
assertThat(credentials.getPassword()).isNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-142
|
||||
@@ -60,34 +59,34 @@ public class UserCredentialsUnitTests {
|
||||
|
||||
UserCredentials credentials = new UserCredentials(null, "password");
|
||||
|
||||
assertThat(credentials.hasUsername(), is(false));
|
||||
assertThat(credentials.getUsername(), is(nullValue()));
|
||||
assertThat(credentials.hasPassword(), is(true));
|
||||
assertThat(credentials.getPassword(), is("password"));
|
||||
assertThat(credentials.hasUsername()).isFalse();
|
||||
assertThat(credentials.getUsername()).isNull();
|
||||
assertThat(credentials.hasPassword()).isTrue();
|
||||
assertThat(credentials.getPassword()).isEqualTo("password");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-275
|
||||
public void returnsNullForNotSetObfuscatedPassword() {
|
||||
assertThat(new UserCredentials(null, null).getObfuscatedPassword(), is(nullValue()));
|
||||
assertThat(new UserCredentials(null, null).getObfuscatedPassword()).isNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-275
|
||||
public void obfuscatesShortPasswordsEntirely() {
|
||||
|
||||
assertThat(new UserCredentials(null, "sa").getObfuscatedPassword(), is("**"));
|
||||
assertThat(new UserCredentials(null, "s").getObfuscatedPassword(), is("*"));
|
||||
assertThat(new UserCredentials(null, "sa").getObfuscatedPassword()).isEqualTo("**");
|
||||
assertThat(new UserCredentials(null, "s").getObfuscatedPassword()).isEqualTo("*");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-275
|
||||
public void returnsObfuscatedPasswordCorrectly() {
|
||||
assertThat(new UserCredentials(null, "password").getObfuscatedPassword(), is("p******d"));
|
||||
assertThat(new UserCredentials(null, "password").getObfuscatedPassword()).isEqualTo("p******d");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-275
|
||||
public void toStringDoesNotExposePlainPassword() {
|
||||
|
||||
UserCredentials credentials = new UserCredentials(null, "mypassword");
|
||||
assertThat(credentials.toString(), not(containsString(credentials.getPassword())));
|
||||
assertThat(credentials.toString(), containsString(credentials.getObfuscatedPassword()));
|
||||
assertThat(credentials.toString()).doesNotContain(credentials.getPassword());
|
||||
assertThat(credentials.toString()).contains(credentials.getObfuscatedPassword());
|
||||
}
|
||||
}
|
||||
|
||||
22
src/test/java/org/springframework/data/config/TypeFilterParserUnitTests.java
Normal file → Executable file
22
src/test/java/org/springframework/data/config/TypeFilterParserUnitTests.java
Normal file → Executable file
@@ -15,16 +15,13 @@
|
||||
*/
|
||||
package org.springframework.data.config;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
|
||||
import org.hamcrest.Matcher;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
@@ -36,7 +33,6 @@ import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.type.filter.AssignableTypeFilter;
|
||||
import org.springframework.core.type.filter.TypeFilter;
|
||||
import org.springframework.data.config.TypeFilterParser;
|
||||
import org.springframework.data.config.TypeFilterParser.Type;
|
||||
import org.springframework.util.xml.DomUtils;
|
||||
import org.w3c.dom.Element;
|
||||
@@ -50,19 +46,13 @@ import org.xml.sax.SAXException;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class TypeFilterParserUnitTests {
|
||||
|
||||
static final Matcher<Iterable<? super AssignableTypeFilter>> IS_ASSIGNABLE_TYPE_FILTER = hasItem(Matchers
|
||||
.isA(AssignableTypeFilter.class));
|
||||
|
||||
TypeFilterParser parser;
|
||||
Element documentElement;
|
||||
|
||||
@Mock
|
||||
ReaderContext context;
|
||||
@Mock
|
||||
ClassLoader classLoader;
|
||||
@Mock ReaderContext context;
|
||||
@Mock ClassLoader classLoader;
|
||||
|
||||
@Mock
|
||||
ClassPathScanningCandidateComponentProvider scanner;
|
||||
@Mock ClassPathScanningCandidateComponentProvider scanner;
|
||||
|
||||
@Before
|
||||
public void setUp() throws SAXException, IOException, ParserConfigurationException {
|
||||
@@ -83,7 +73,7 @@ public class TypeFilterParserUnitTests {
|
||||
Element element = DomUtils.getChildElementByTagName(documentElement, "firstSample");
|
||||
|
||||
Iterable<TypeFilter> filters = parser.parseTypeFilters(element, Type.INCLUDE);
|
||||
assertThat(filters, IS_ASSIGNABLE_TYPE_FILTER);
|
||||
assertThat(filters).hasAtLeastOneElementOfType(AssignableTypeFilter.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -92,6 +82,6 @@ public class TypeFilterParserUnitTests {
|
||||
Element element = DomUtils.getChildElementByTagName(documentElement, "secondSample");
|
||||
|
||||
Iterable<TypeFilter> filters = parser.parseTypeFilters(element, Type.EXCLUDE);
|
||||
assertThat(filters, IS_ASSIGNABLE_TYPE_FILTER);
|
||||
assertThat(filters).hasAtLeastOneElementOfType(AssignableTypeFilter.class);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,385 +0,0 @@
|
||||
/*
|
||||
* Copyright 2014-2017 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.convert;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.data.convert.BytecodeGeneratingEntityInstantiator.*;
|
||||
import static org.springframework.data.util.ClassTypeInformation.*;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.convert.BytecodeGeneratingEntityInstantiatorUnitTests.Outer.Inner;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.mapping.PersistentProperty;
|
||||
import org.springframework.data.mapping.PreferredConstructor;
|
||||
import org.springframework.data.mapping.PreferredConstructor.Parameter;
|
||||
import org.springframework.data.mapping.model.BasicPersistentEntity;
|
||||
import org.springframework.data.mapping.model.MappingInstantiationException;
|
||||
import org.springframework.data.mapping.model.ParameterValueProvider;
|
||||
import org.springframework.data.mapping.model.PreferredConstructorDiscoverer;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springframework.util.ReflectionUtils.FieldCallback;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link BytecodeGeneratingEntityInstantiator}.
|
||||
*
|
||||
* @author Thomas Darimont
|
||||
* @author Oliver Gierke
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
@Deprecated
|
||||
public class BytecodeGeneratingEntityInstantiatorUnitTests<P extends PersistentProperty<P>> {
|
||||
|
||||
@Mock PersistentEntity<?, P> entity;
|
||||
@Mock ParameterValueProvider<P> provider;
|
||||
@Mock PreferredConstructor<?, P> constructor;
|
||||
@Mock Parameter<?, P> parameter;
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiatesSimpleObjectCorrectly() {
|
||||
|
||||
when(entity.getType()).thenReturn((Class) Object.class);
|
||||
INSTANCE.createInstance(entity, provider);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiatesArrayCorrectly() {
|
||||
|
||||
when(entity.getType()).thenReturn((Class) String[][].class);
|
||||
INSTANCE.createInstance(entity, provider);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiatesTypeWithPreferredConstructorUsingParameterValueProvider() {
|
||||
|
||||
PreferredConstructor constructor = new PreferredConstructorDiscoverer<Foo, P>(Foo.class).getConstructor();
|
||||
|
||||
when(entity.getType()).thenReturn((Class) Foo.class);
|
||||
when(entity.getPersistenceConstructor()).thenReturn(constructor);
|
||||
|
||||
Object instance = INSTANCE.createInstance(entity, provider);
|
||||
|
||||
assertTrue(instance instanceof Foo);
|
||||
verify(provider, times(1)).getParameterValue((Parameter) constructor.getParameters().iterator().next());
|
||||
}
|
||||
|
||||
@Test(expected = MappingInstantiationException.class) // DATACMNS-300, DATACMNS-578
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void throwsExceptionOnBeanInstantiationException() {
|
||||
|
||||
when(entity.getPersistenceConstructor()).thenReturn(null);
|
||||
when(entity.getType()).thenReturn((Class) PersistentEntity.class);
|
||||
|
||||
INSTANCE.createInstance(entity, provider);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-134, DATACMNS-578
|
||||
public void createsInnerClassInstanceCorrectly() {
|
||||
|
||||
BasicPersistentEntity<Inner, P> entity = new BasicPersistentEntity<Inner, P>(from(Inner.class));
|
||||
PreferredConstructor<Inner, P> constructor = entity.getPersistenceConstructor();
|
||||
Parameter<Object, P> parameter = constructor.getParameters().iterator().next();
|
||||
|
||||
final Object outer = new Outer();
|
||||
|
||||
when(provider.getParameterValue(parameter)).thenReturn(outer);
|
||||
final Inner instance = INSTANCE.createInstance(entity, provider);
|
||||
|
||||
assertThat(instance, is(notNullValue()));
|
||||
|
||||
// Hack to check syntheic field as compiles create different field names (e.g. this$0, this$1)
|
||||
ReflectionUtils.doWithFields(Inner.class, new FieldCallback() {
|
||||
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
|
||||
if (field.isSynthetic() && field.getName().startsWith("this$")) {
|
||||
ReflectionUtils.makeAccessible(field);
|
||||
assertThat(ReflectionUtils.getField(field, instance), is(outer));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-283, DATACMNS-578
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void capturesContextOnInstantiationException() throws Exception {
|
||||
|
||||
PersistentEntity<Sample, P> entity = new BasicPersistentEntity<Sample, P>(from(Sample.class));
|
||||
|
||||
when(provider.getParameterValue(Mockito.any(Parameter.class))).thenReturn("FOO");
|
||||
|
||||
Constructor constructor = Sample.class.getConstructor(Long.class, String.class);
|
||||
List<Object> parameters = Arrays.asList((Object) "FOO", (Object) "FOO");
|
||||
|
||||
try {
|
||||
|
||||
INSTANCE.createInstance(entity, provider);
|
||||
fail("Expected MappingInstantiationException!");
|
||||
|
||||
} catch (MappingInstantiationException o_O) {
|
||||
|
||||
assertThat(o_O.getConstructor(), is(constructor));
|
||||
assertThat(o_O.getConstructorArguments(), is(parameters));
|
||||
assertEquals(Sample.class, o_O.getEntityType());
|
||||
|
||||
assertThat(o_O.getMessage(), containsString(Sample.class.getName()));
|
||||
assertThat(o_O.getMessage(), containsString(Long.class.getName()));
|
||||
assertThat(o_O.getMessage(), containsString(String.class.getName()));
|
||||
assertThat(o_O.getMessage(), containsString("FOO"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test // DATACMNS-578
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiateObjCtorDefault() {
|
||||
|
||||
PreferredConstructor constructor = new PreferredConstructorDiscoverer<ObjCtorDefault, P>(ObjCtorDefault.class)
|
||||
.getConstructor();
|
||||
|
||||
when(entity.getType()).thenReturn((Class) ObjCtorDefault.class);
|
||||
when(entity.getPersistenceConstructor()).thenReturn(constructor);
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
Object instance = INSTANCE.createInstance(entity, provider);
|
||||
assertTrue(instance instanceof ObjCtorDefault);
|
||||
}
|
||||
}
|
||||
|
||||
@Test // DATACMNS-578
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiateObjCtorNoArgs() {
|
||||
|
||||
PreferredConstructor constructor = new PreferredConstructorDiscoverer<ObjCtorNoArgs, P>(ObjCtorNoArgs.class)
|
||||
.getConstructor();
|
||||
|
||||
when(entity.getType()).thenReturn((Class) ObjCtorNoArgs.class);
|
||||
when(entity.getPersistenceConstructor()).thenReturn(constructor);
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
Object instance = INSTANCE.createInstance(entity, provider);
|
||||
assertTrue(instance instanceof ObjCtorNoArgs);
|
||||
assertTrue(((ObjCtorNoArgs) instance).ctorInvoked);
|
||||
}
|
||||
}
|
||||
|
||||
@Test // DATACMNS-578
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiateObjCtor1ParamString() {
|
||||
|
||||
PreferredConstructor constructor = new PreferredConstructorDiscoverer<ObjCtor1ParamString, P>(
|
||||
ObjCtor1ParamString.class).getConstructor();
|
||||
|
||||
when(entity.getType()).thenReturn((Class) ObjCtor1ParamString.class);
|
||||
when(entity.getPersistenceConstructor()).thenReturn(constructor);
|
||||
|
||||
when(provider.getParameterValue(Mockito.any(Parameter.class))).thenReturn("FOO");
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
Object instance = INSTANCE.createInstance(entity, provider);
|
||||
assertTrue(instance instanceof ObjCtor1ParamString);
|
||||
assertTrue(((ObjCtor1ParamString) instance).ctorInvoked);
|
||||
assertThat(((ObjCtor1ParamString) instance).param1, is("FOO"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test // DATACMNS-578
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiateObjCtor2ParamStringString() {
|
||||
|
||||
PreferredConstructor constructor = new PreferredConstructorDiscoverer<ObjCtor2ParamStringString, P>(
|
||||
ObjCtor2ParamStringString.class).getConstructor();
|
||||
|
||||
when(entity.getType()).thenReturn((Class) ObjCtor2ParamStringString.class);
|
||||
when(entity.getPersistenceConstructor()).thenReturn(constructor);
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
when(provider.getParameterValue(Mockito.any(Parameter.class))).thenReturn("FOO").thenReturn("BAR");
|
||||
|
||||
Object instance = INSTANCE.createInstance(entity, provider);
|
||||
assertTrue(instance instanceof ObjCtor2ParamStringString);
|
||||
assertTrue(((ObjCtor2ParamStringString) instance).ctorInvoked);
|
||||
assertThat(((ObjCtor2ParamStringString) instance).param1, is("FOO"));
|
||||
assertThat(((ObjCtor2ParamStringString) instance).param2, is("BAR"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test // DATACMNS-578
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiateObjectCtor1ParamInt() {
|
||||
|
||||
PreferredConstructor constructor = new PreferredConstructorDiscoverer<ObjectCtor1ParamInt, P>(
|
||||
ObjectCtor1ParamInt.class).getConstructor();
|
||||
|
||||
when(entity.getType()).thenReturn((Class) ObjectCtor1ParamInt.class);
|
||||
when(entity.getPersistenceConstructor()).thenReturn(constructor);
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
|
||||
when(provider.getParameterValue(Mockito.any(Parameter.class))).thenReturn(42);
|
||||
|
||||
Object instance = INSTANCE.createInstance(entity, provider);
|
||||
assertTrue(instance instanceof ObjectCtor1ParamInt);
|
||||
assertTrue("matches", ((ObjectCtor1ParamInt) instance).param1 == 42);
|
||||
}
|
||||
}
|
||||
|
||||
@Test // DATACMNS-578
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiateObjectCtor7ParamsString5IntsString() {
|
||||
|
||||
PreferredConstructor constructor = new PreferredConstructorDiscoverer<ObjectCtor7ParamsString5IntsString, P>(
|
||||
ObjectCtor7ParamsString5IntsString.class).getConstructor();
|
||||
|
||||
when(entity.getType()).thenReturn((Class) ObjectCtor7ParamsString5IntsString.class);
|
||||
when(entity.getPersistenceConstructor()).thenReturn(constructor);
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
when(provider.getParameterValue(Mockito.any(Parameter.class))).thenReturn("A").thenReturn(1).thenReturn(2)
|
||||
.thenReturn(3).thenReturn(4).thenReturn(5).thenReturn("B");
|
||||
|
||||
Object instance = INSTANCE.createInstance(entity, provider);
|
||||
assertTrue(instance instanceof ObjectCtor7ParamsString5IntsString);
|
||||
assertThat(((ObjectCtor7ParamsString5IntsString) instance).param1, is("A"));
|
||||
assertThat(((ObjectCtor7ParamsString5IntsString) instance).param2, is(1));
|
||||
assertThat(((ObjectCtor7ParamsString5IntsString) instance).param3, is(2));
|
||||
assertThat(((ObjectCtor7ParamsString5IntsString) instance).param4, is(3));
|
||||
assertThat(((ObjectCtor7ParamsString5IntsString) instance).param5, is(4));
|
||||
assertThat(((ObjectCtor7ParamsString5IntsString) instance).param6, is(5));
|
||||
assertThat(((ObjectCtor7ParamsString5IntsString) instance).param7, is("B"));
|
||||
}
|
||||
}
|
||||
|
||||
static class Foo {
|
||||
|
||||
Foo(String foo) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
static class Outer {
|
||||
|
||||
class Inner {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
static class Sample {
|
||||
|
||||
final Long id;
|
||||
final String name;
|
||||
|
||||
public Sample(Long id, String name) {
|
||||
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Thomas Darimont
|
||||
*/
|
||||
public static class ObjCtorDefault {}
|
||||
|
||||
/**
|
||||
* @author Thomas Darimont
|
||||
*/
|
||||
public static class ObjCtorNoArgs {
|
||||
|
||||
public boolean ctorInvoked;
|
||||
|
||||
public ObjCtorNoArgs() {
|
||||
ctorInvoked = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Thomas Darimont
|
||||
*/
|
||||
public static class ObjCtor1ParamString {
|
||||
|
||||
public boolean ctorInvoked;
|
||||
public String param1;
|
||||
|
||||
public ObjCtor1ParamString(String param1) {
|
||||
this.param1 = param1;
|
||||
this.ctorInvoked = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Thomas Darimont
|
||||
*/
|
||||
public static class ObjCtor2ParamStringString {
|
||||
|
||||
public boolean ctorInvoked;
|
||||
public String param1;
|
||||
public String param2;
|
||||
|
||||
public ObjCtor2ParamStringString(String param1, String param2) {
|
||||
this.ctorInvoked = true;
|
||||
this.param1 = param1;
|
||||
this.param2 = param2;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Thomas Darimont
|
||||
*/
|
||||
public static class ObjectCtor1ParamInt {
|
||||
|
||||
public int param1;
|
||||
|
||||
public ObjectCtor1ParamInt(int param1) {
|
||||
this.param1 = param1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Thomas Darimont
|
||||
*/
|
||||
public static class ObjectCtor7ParamsString5IntsString {
|
||||
|
||||
public String param1;
|
||||
public int param2;
|
||||
public int param3;
|
||||
public int param4;
|
||||
public int param5;
|
||||
public int param6;
|
||||
public String param7;
|
||||
|
||||
public ObjectCtor7ParamsString5IntsString(String param1, int param2, int param3, int param4, int param5,
|
||||
int param6, String param7) {
|
||||
this.param1 = param1;
|
||||
this.param2 = param2;
|
||||
this.param3 = param3;
|
||||
this.param4 = param4;
|
||||
this.param5 = param5;
|
||||
this.param6 = param6;
|
||||
this.param7 = param7;
|
||||
}
|
||||
}
|
||||
}
|
||||
232
src/test/java/org/springframework/data/convert/ClassGeneratingEntityInstantiatorUnitTests.java
Normal file → Executable file
232
src/test/java/org/springframework/data/convert/ClassGeneratingEntityInstantiatorUnitTests.java
Normal file → Executable file
@@ -15,20 +15,23 @@
|
||||
*/
|
||||
package org.springframework.data.convert;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.data.util.ClassTypeInformation.*;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.convert.ClassGeneratingEntityInstantiatorUnitTests.Outer.Inner;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
@@ -40,7 +43,6 @@ import org.springframework.data.mapping.model.MappingInstantiationException;
|
||||
import org.springframework.data.mapping.model.ParameterValueProvider;
|
||||
import org.springframework.data.mapping.model.PreferredConstructorDiscoverer;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springframework.util.ReflectionUtils.FieldCallback;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link ClassGeneratingEntityInstantiator}.
|
||||
@@ -58,43 +60,49 @@ public class ClassGeneratingEntityInstantiatorUnitTests<P extends PersistentProp
|
||||
@Mock PreferredConstructor<?, P> constructor;
|
||||
@Mock Parameter<?, P> parameter;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
doReturn(Optional.empty()).when(entity).getPersistenceConstructor();
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiatesSimpleObjectCorrectly() {
|
||||
|
||||
when(entity.getType()).thenReturn((Class) Object.class);
|
||||
doReturn(Object.class).when(entity).getType();
|
||||
|
||||
this.instance.createInstance(entity, provider);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiatesArrayCorrectly() {
|
||||
|
||||
when(entity.getType()).thenReturn((Class) String[][].class);
|
||||
doReturn(String[][].class).when(entity).getType();
|
||||
|
||||
this.instance.createInstance(entity, provider);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiatesTypeWithPreferredConstructorUsingParameterValueProvider() {
|
||||
|
||||
PreferredConstructor constructor = new PreferredConstructorDiscoverer<Foo, P>(Foo.class).getConstructor();
|
||||
Optional<? extends PreferredConstructor<Foo, P>> constructor = new PreferredConstructorDiscoverer<Foo, P>(Foo.class)
|
||||
.getConstructor();
|
||||
|
||||
when(entity.getType()).thenReturn((Class) Foo.class);
|
||||
when(entity.getPersistenceConstructor()).thenReturn(constructor);
|
||||
doReturn(Foo.class).when(entity).getType();
|
||||
doReturn(constructor).when(entity).getPersistenceConstructor();
|
||||
|
||||
Object instance = this.instance.createInstance(entity, provider);
|
||||
assertThat(instance.createInstance(entity, provider)).isInstanceOf(Foo.class);
|
||||
|
||||
assertTrue(instance instanceof Foo);
|
||||
verify(provider, times(1)).getParameterValue((Parameter) constructor.getParameters().iterator().next());
|
||||
assertThat(constructor).hasValueSatisfying(it -> {
|
||||
verify(provider, times(1)).getParameterValue(it.getParameters().iterator().next());
|
||||
});
|
||||
}
|
||||
|
||||
@Test(expected = MappingInstantiationException.class) // DATACMNS-300, DATACMNS-578
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void throwsExceptionOnBeanInstantiationException() {
|
||||
|
||||
when(entity.getPersistenceConstructor()).thenReturn(null);
|
||||
when(entity.getType()).thenReturn((Class) PersistentEntity.class);
|
||||
doReturn(Optional.empty()).when(entity).getPersistenceConstructor();
|
||||
doReturn(PersistentEntity.class).when(entity).getType();
|
||||
|
||||
this.instance.createInstance(entity, provider);
|
||||
}
|
||||
@@ -103,24 +111,24 @@ public class ClassGeneratingEntityInstantiatorUnitTests<P extends PersistentProp
|
||||
public void createsInnerClassInstanceCorrectly() {
|
||||
|
||||
BasicPersistentEntity<Inner, P> entity = new BasicPersistentEntity<Inner, P>(from(Inner.class));
|
||||
PreferredConstructor<Inner, P> constructor = entity.getPersistenceConstructor();
|
||||
Parameter<Object, P> parameter = constructor.getParameters().iterator().next();
|
||||
assertThat(entity.getPersistenceConstructor()).hasValueSatisfying(constructor -> {
|
||||
|
||||
final Object outer = new Outer();
|
||||
Parameter<Object, P> parameter = constructor.getParameters().iterator().next();
|
||||
|
||||
when(provider.getParameterValue(parameter)).thenReturn(outer);
|
||||
final Inner instance = this.instance.createInstance(entity, provider);
|
||||
Object outer = new Outer();
|
||||
|
||||
assertThat(instance, is(notNullValue()));
|
||||
doReturn(Optional.of(outer)).when(provider).getParameterValue(parameter);
|
||||
Inner instance = this.instance.createInstance(entity, provider);
|
||||
|
||||
// Hack to check syntheic field as compiles create different field names (e.g. this$0, this$1)
|
||||
ReflectionUtils.doWithFields(Inner.class, new FieldCallback() {
|
||||
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
|
||||
assertThat(instance).isNotNull();
|
||||
|
||||
// Hack to check synthetic field as compiles create different field names (e.g. this$0, this$1)
|
||||
ReflectionUtils.doWithFields(Inner.class, field -> {
|
||||
if (field.isSynthetic() && field.getName().startsWith("this$")) {
|
||||
ReflectionUtils.makeAccessible(field);
|
||||
assertThat(ReflectionUtils.getField(field, instance), is(outer));
|
||||
assertThat(ReflectionUtils.getField(field, instance)).isEqualTo(outer);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -128,12 +136,12 @@ public class ClassGeneratingEntityInstantiatorUnitTests<P extends PersistentProp
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void capturesContextOnInstantiationException() throws Exception {
|
||||
|
||||
PersistentEntity<Sample, P> entity = new BasicPersistentEntity<Sample, P>(from(Sample.class));
|
||||
PersistentEntity<Sample, P> entity = new BasicPersistentEntity<>(from(Sample.class));
|
||||
|
||||
when(provider.getParameterValue(Mockito.any(Parameter.class))).thenReturn("FOO");
|
||||
doReturn(Optional.of("FOO")).when(provider).getParameterValue(any(Parameter.class));
|
||||
|
||||
Constructor constructor = Sample.class.getConstructor(Long.class, String.class);
|
||||
List<Object> parameters = Arrays.asList((Object) "FOO", (Object) "FOO");
|
||||
List<Object> parameters = Arrays.asList("FOO", "FOO");
|
||||
|
||||
try {
|
||||
|
||||
@@ -142,14 +150,14 @@ public class ClassGeneratingEntityInstantiatorUnitTests<P extends PersistentProp
|
||||
|
||||
} catch (MappingInstantiationException o_O) {
|
||||
|
||||
assertThat(o_O.getConstructor(), is(constructor));
|
||||
assertThat(o_O.getConstructorArguments(), is(parameters));
|
||||
assertEquals(Sample.class, o_O.getEntityType());
|
||||
assertThat(o_O.getConstructor()).hasValue(constructor);
|
||||
assertThat(o_O.getConstructorArguments()).isEqualTo(parameters);
|
||||
assertThat(o_O.getEntityType()).hasValue(Sample.class);
|
||||
|
||||
assertThat(o_O.getMessage(), containsString(Sample.class.getName()));
|
||||
assertThat(o_O.getMessage(), containsString(Long.class.getName()));
|
||||
assertThat(o_O.getMessage(), containsString(String.class.getName()));
|
||||
assertThat(o_O.getMessage(), containsString("FOO"));
|
||||
assertThat(o_O.getMessage()).contains(Sample.class.getName());
|
||||
assertThat(o_O.getMessage()).contains(Long.class.getName());
|
||||
assertThat(o_O.getMessage()).contains(String.class.getName());
|
||||
assertThat(o_O.getMessage()).contains("FOO");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,120 +165,124 @@ public class ClassGeneratingEntityInstantiatorUnitTests<P extends PersistentProp
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiateObjCtorDefault() {
|
||||
|
||||
PreferredConstructor constructor = new PreferredConstructorDiscoverer<ObjCtorDefault, P>(ObjCtorDefault.class)
|
||||
.getConstructor();
|
||||
doReturn(ObjCtorDefault.class).when(entity).getType();
|
||||
doReturn(new PreferredConstructorDiscoverer<>(ObjCtorDefault.class).getConstructor())//
|
||||
.when(entity).getPersistenceConstructor();
|
||||
|
||||
when(entity.getType()).thenReturn((Class) ObjCtorDefault.class);
|
||||
when(entity.getPersistenceConstructor()).thenReturn(constructor);
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
Object instance = this.instance.createInstance(entity, provider);
|
||||
assertTrue(instance instanceof ObjCtorDefault);
|
||||
}
|
||||
IntStream.range(0, 2).forEach(i -> {
|
||||
assertThat(this.instance.createInstance(entity, provider)).isInstanceOf(ObjCtorDefault.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-578
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiateObjCtorNoArgs() {
|
||||
|
||||
PreferredConstructor constructor = new PreferredConstructorDiscoverer<ObjCtorNoArgs, P>(ObjCtorNoArgs.class)
|
||||
.getConstructor();
|
||||
doReturn(ObjCtorNoArgs.class).when(entity).getType();
|
||||
doReturn(new PreferredConstructorDiscoverer<>(ObjCtorNoArgs.class).getConstructor())//
|
||||
.when(entity).getPersistenceConstructor();
|
||||
|
||||
when(entity.getType()).thenReturn((Class) ObjCtorNoArgs.class);
|
||||
when(entity.getPersistenceConstructor()).thenReturn(constructor);
|
||||
IntStream.range(0, 2).forEach(i -> {
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
Object instance = this.instance.createInstance(entity, provider);
|
||||
assertTrue(instance instanceof ObjCtorNoArgs);
|
||||
assertTrue(((ObjCtorNoArgs) instance).ctorInvoked);
|
||||
}
|
||||
|
||||
assertThat(instance).isInstanceOf(ObjCtorNoArgs.class);
|
||||
assertThat(((ObjCtorNoArgs) instance).ctorInvoked).isTrue();
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-578
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
@SuppressWarnings("unchecked")
|
||||
public void instantiateObjCtor1ParamString() {
|
||||
|
||||
PreferredConstructor constructor = new PreferredConstructorDiscoverer<ObjCtor1ParamString, P>(
|
||||
ObjCtor1ParamString.class).getConstructor();
|
||||
doReturn(ObjCtor1ParamString.class).when(entity).getType();
|
||||
doReturn(new PreferredConstructorDiscoverer<>(ObjCtor1ParamString.class).getConstructor())//
|
||||
.when(entity).getPersistenceConstructor();
|
||||
doReturn(Optional.of("FOO")).when(provider).getParameterValue(any());
|
||||
|
||||
when(entity.getType()).thenReturn((Class) ObjCtor1ParamString.class);
|
||||
when(entity.getPersistenceConstructor()).thenReturn(constructor);
|
||||
IntStream.range(0, 2).forEach(i -> {
|
||||
|
||||
when(provider.getParameterValue(Mockito.any(Parameter.class))).thenReturn("FOO");
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
Object instance = this.instance.createInstance(entity, provider);
|
||||
assertTrue(instance instanceof ObjCtor1ParamString);
|
||||
assertTrue(((ObjCtor1ParamString) instance).ctorInvoked);
|
||||
assertThat(((ObjCtor1ParamString) instance).param1, is("FOO"));
|
||||
}
|
||||
|
||||
assertThat(instance).isInstanceOf(ObjCtor1ParamString.class);
|
||||
assertThat(((ObjCtor1ParamString) instance).ctorInvoked).isTrue();
|
||||
assertThat(((ObjCtor1ParamString) instance).param1).isEqualTo("FOO");
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-578
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
@SuppressWarnings("unchecked")
|
||||
public void instantiateObjCtor2ParamStringString() {
|
||||
|
||||
PreferredConstructor constructor = new PreferredConstructorDiscoverer<ObjCtor2ParamStringString, P>(
|
||||
ObjCtor2ParamStringString.class).getConstructor();
|
||||
doReturn(ObjCtor2ParamStringString.class).when(entity).getType();
|
||||
doReturn(new PreferredConstructorDiscoverer<>(ObjCtor2ParamStringString.class).getConstructor())//
|
||||
.when(entity).getPersistenceConstructor();
|
||||
|
||||
when(entity.getType()).thenReturn((Class) ObjCtor2ParamStringString.class);
|
||||
when(entity.getPersistenceConstructor()).thenReturn(constructor);
|
||||
IntStream.range(0, 2).forEach(i -> {
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
when(provider.getParameterValue(Mockito.any(Parameter.class))).thenReturn("FOO").thenReturn("BAR");
|
||||
when(provider.getParameterValue(any())).thenReturn(Optional.of("FOO"), Optional.of("BAR"));
|
||||
|
||||
Object instance = this.instance.createInstance(entity, provider);
|
||||
assertTrue(instance instanceof ObjCtor2ParamStringString);
|
||||
assertTrue(((ObjCtor2ParamStringString) instance).ctorInvoked);
|
||||
assertThat(((ObjCtor2ParamStringString) instance).param1, is("FOO"));
|
||||
assertThat(((ObjCtor2ParamStringString) instance).param2, is("BAR"));
|
||||
}
|
||||
|
||||
assertThat(instance).isInstanceOf(ObjCtor2ParamStringString.class);
|
||||
assertThat(((ObjCtor2ParamStringString) instance).ctorInvoked).isTrue();
|
||||
assertThat(((ObjCtor2ParamStringString) instance).param1).isEqualTo("FOO");
|
||||
assertThat(((ObjCtor2ParamStringString) instance).param2).isEqualTo("BAR");
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-578
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
@SuppressWarnings("unchecked")
|
||||
public void instantiateObjectCtor1ParamInt() {
|
||||
|
||||
PreferredConstructor constructor = new PreferredConstructorDiscoverer<ObjectCtor1ParamInt, P>(
|
||||
ObjectCtor1ParamInt.class).getConstructor();
|
||||
doReturn(ObjectCtor1ParamInt.class).when(entity).getType();
|
||||
doReturn(new PreferredConstructorDiscoverer<>(ObjectCtor1ParamInt.class).getConstructor())//
|
||||
.when(entity).getPersistenceConstructor();
|
||||
|
||||
when(entity.getType()).thenReturn((Class) ObjectCtor1ParamInt.class);
|
||||
when(entity.getPersistenceConstructor()).thenReturn(constructor);
|
||||
IntStream.range(0, 2).forEach(i -> {
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
|
||||
when(provider.getParameterValue(Mockito.any(Parameter.class))).thenReturn(42);
|
||||
doReturn(Optional.of(42)).when(provider).getParameterValue(any());
|
||||
|
||||
Object instance = this.instance.createInstance(entity, provider);
|
||||
assertTrue(instance instanceof ObjectCtor1ParamInt);
|
||||
assertTrue("matches", ((ObjectCtor1ParamInt) instance).param1 == 42);
|
||||
}
|
||||
|
||||
assertThat(instance).isInstanceOf(ObjectCtor1ParamInt.class);
|
||||
assertThat(((ObjectCtor1ParamInt) instance).param1).isEqualTo(42);
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-578
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
@SuppressWarnings("unchecked")
|
||||
public void instantiateObjectCtor7ParamsString5IntsString() {
|
||||
|
||||
PreferredConstructor constructor = new PreferredConstructorDiscoverer<ObjectCtor7ParamsString5IntsString, P>(
|
||||
ObjectCtor7ParamsString5IntsString.class).getConstructor();
|
||||
doReturn(ObjectCtor7ParamsString5IntsString.class).when(entity).getType();
|
||||
doReturn(new PreferredConstructorDiscoverer<>(ObjectCtor7ParamsString5IntsString.class).getConstructor())//
|
||||
.when(entity).getPersistenceConstructor();
|
||||
|
||||
when(entity.getType()).thenReturn((Class) ObjectCtor7ParamsString5IntsString.class);
|
||||
when(entity.getPersistenceConstructor()).thenReturn(constructor);
|
||||
IntStream.range(0, 2).forEach(i -> {
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
when(provider.getParameterValue(Mockito.any(Parameter.class))).thenReturn("A").thenReturn(1).thenReturn(2)
|
||||
.thenReturn(3).thenReturn(4).thenReturn(5).thenReturn("B");
|
||||
when(provider.getParameterValue(any(Parameter.class))).thenReturn(Optional.of("A"), Optional.of(1),
|
||||
Optional.of(2), Optional.of(3), Optional.of(4), Optional.of(5), Optional.of("B"));
|
||||
|
||||
Object instance = this.instance.createInstance(entity, provider);
|
||||
assertTrue(instance instanceof ObjectCtor7ParamsString5IntsString);
|
||||
assertThat(((ObjectCtor7ParamsString5IntsString) instance).param1, is("A"));
|
||||
assertThat(((ObjectCtor7ParamsString5IntsString) instance).param2, is(1));
|
||||
assertThat(((ObjectCtor7ParamsString5IntsString) instance).param3, is(2));
|
||||
assertThat(((ObjectCtor7ParamsString5IntsString) instance).param4, is(3));
|
||||
assertThat(((ObjectCtor7ParamsString5IntsString) instance).param5, is(4));
|
||||
assertThat(((ObjectCtor7ParamsString5IntsString) instance).param6, is(5));
|
||||
assertThat(((ObjectCtor7ParamsString5IntsString) instance).param7, is("B"));
|
||||
}
|
||||
|
||||
assertThat(instance).isInstanceOf(ObjectCtor7ParamsString5IntsString.class);
|
||||
|
||||
ObjectCtor7ParamsString5IntsString toTest = (ObjectCtor7ParamsString5IntsString) instance;
|
||||
|
||||
assertThat(toTest.param1).isEqualTo("A");
|
||||
assertThat(toTest.param2).isEqualTo(1);
|
||||
assertThat(toTest.param3).isEqualTo(2);
|
||||
assertThat(toTest.param4).isEqualTo(3);
|
||||
assertThat(toTest.param5).isEqualTo(4);
|
||||
assertThat(toTest.param6).isEqualTo(5);
|
||||
assertThat(toTest.param7).isEqualTo("B");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testname() {
|
||||
|
||||
List<String> result = Stream.of("1", null).map(it -> (String) null).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
static class Foo {
|
||||
@@ -371,8 +383,8 @@ public class ClassGeneratingEntityInstantiatorUnitTests<P extends PersistentProp
|
||||
public int param6;
|
||||
public String param7;
|
||||
|
||||
public ObjectCtor7ParamsString5IntsString(String param1, int param2, int param3, int param4, int param5,
|
||||
int param6, String param7) {
|
||||
public ObjectCtor7ParamsString5IntsString(String param1, int param2, int param3, int param4, int param5, int param6,
|
||||
String param7) {
|
||||
this.param1 = param1;
|
||||
this.param2 = param2;
|
||||
this.param3 = param3;
|
||||
|
||||
11
src/test/java/org/springframework/data/convert/ConfigurableTypeInformationMapperUnitTests.java
Normal file → Executable file
11
src/test/java/org/springframework/data/convert/ConfigurableTypeInformationMapperUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.convert;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
@@ -63,15 +62,15 @@ public class ConfigurableTypeInformationMapperUnitTests<T extends PersistentProp
|
||||
@Test
|
||||
public void writesMapKeyForType() {
|
||||
|
||||
assertThat(mapper.createAliasFor(ClassTypeInformation.from(String.class)), is((Object) "1"));
|
||||
assertThat(mapper.createAliasFor(ClassTypeInformation.from(Object.class)), is(nullValue()));
|
||||
assertThat(mapper.createAliasFor(ClassTypeInformation.from(String.class))).isEqualTo("1");
|
||||
assertThat(mapper.createAliasFor(ClassTypeInformation.from(Object.class))).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("rawtypes")
|
||||
public void readsTypeForMapKey() {
|
||||
|
||||
assertThat(mapper.resolveTypeFrom("1"), is((TypeInformation) ClassTypeInformation.from(String.class)));
|
||||
assertThat(mapper.resolveTypeFrom("unmapped"), is(nullValue()));
|
||||
assertThat(mapper.resolveTypeFrom("1")).isEqualTo((TypeInformation) ClassTypeInformation.from(String.class));
|
||||
assertThat(mapper.resolveTypeFrom("unmapped")).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
11
src/test/java/org/springframework/data/convert/DefaultTypeMapperUnitTests.java
Normal file → Executable file
11
src/test/java/org/springframework/data/convert/DefaultTypeMapperUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.convert;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
@@ -64,7 +63,7 @@ public class DefaultTypeMapperUnitTests {
|
||||
public void cachesResolvedTypeInformation() {
|
||||
|
||||
TypeInformation<?> information = typeMapper.readType(source);
|
||||
assertThat(information, is((TypeInformation) STRING_TYPE_INFO));
|
||||
assertThat(information).isEqualTo((TypeInformation) STRING_TYPE_INFO);
|
||||
verify(mapper, times(1)).resolveTypeFrom(STRING);
|
||||
|
||||
typeMapper.readType(source);
|
||||
@@ -77,7 +76,7 @@ public class DefaultTypeMapperUnitTests {
|
||||
Object alias = "alias";
|
||||
when(mapper.createAliasFor(STRING_TYPE_INFO)).thenReturn(alias);
|
||||
|
||||
assertThat(this.typeMapper.getAliasFor(STRING_TYPE_INFO), is(alias));
|
||||
assertThat(this.typeMapper.getAliasFor(STRING_TYPE_INFO)).isEqualTo(alias);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-783
|
||||
@@ -92,8 +91,8 @@ public class DefaultTypeMapperUnitTests {
|
||||
|
||||
TypeInformation<?> result = typeMapper.readType(source, propertyType);
|
||||
|
||||
assertThat(result.getType(), is((Object) Bar.class));
|
||||
assertThat(result.getProperty("field").getType(), is((Object) Character.class));
|
||||
assertThat(result.getType()).isEqualTo(Bar.class);
|
||||
assertThat(result.getProperty("field").getType()).isEqualTo(Character.class);
|
||||
}
|
||||
|
||||
static class TypeWithAbstractGenericType<T> {
|
||||
|
||||
29
src/test/java/org/springframework/data/convert/EntityInstantiatorsUnitTests.java
Normal file → Executable file
29
src/test/java/org/springframework/data/convert/EntityInstantiatorsUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.convert;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Collections;
|
||||
@@ -48,38 +47,36 @@ public class EntityInstantiatorsUnitTests {
|
||||
public void usesReflectionEntityInstantiatorAsDefaultFallback() {
|
||||
|
||||
EntityInstantiators instantiators = new EntityInstantiators();
|
||||
assertThat(instantiators.getInstantiatorFor(entity),
|
||||
instanceOf(ClassGeneratingEntityInstantiator.class));
|
||||
assertThat(instantiators.getInstantiatorFor(entity)).isInstanceOf(ClassGeneratingEntityInstantiator.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void returnsCustomInstantiatorForTypeIfRegistered() {
|
||||
|
||||
when(entity.getType()).thenReturn((Class) String.class);
|
||||
doReturn(String.class).when(entity).getType();
|
||||
|
||||
Map<Class<?>, EntityInstantiator> customInstantiators = Collections.<Class<?>, EntityInstantiator> singletonMap(
|
||||
String.class, customInstantiator);
|
||||
Map<Class<?>, EntityInstantiator> customInstantiators = Collections
|
||||
.<Class<?>, EntityInstantiator> singletonMap(String.class, customInstantiator);
|
||||
|
||||
EntityInstantiators instantiators = new EntityInstantiators(customInstantiators);
|
||||
assertThat(instantiators.getInstantiatorFor(entity), is(customInstantiator));
|
||||
assertThat(instantiators.getInstantiatorFor(entity)).isEqualTo(customInstantiator);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void usesCustomFallbackInstantiatorsIfConfigured() {
|
||||
|
||||
when(entity.getType()).thenReturn((Class) Object.class);
|
||||
doReturn(Object.class).when(entity).getType();
|
||||
|
||||
Map<Class<?>, EntityInstantiator> customInstantiators = Collections.<Class<?>, EntityInstantiator> singletonMap(
|
||||
String.class, ReflectionEntityInstantiator.INSTANCE);
|
||||
Map<Class<?>, EntityInstantiator> customInstantiators = Collections
|
||||
.<Class<?>, EntityInstantiator> singletonMap(String.class, ReflectionEntityInstantiator.INSTANCE);
|
||||
|
||||
EntityInstantiators instantiators = new EntityInstantiators(customInstantiator, customInstantiators);
|
||||
instantiators.getInstantiatorFor(entity);
|
||||
|
||||
assertThat(instantiators.getInstantiatorFor(entity), is(customInstantiator));
|
||||
assertThat(instantiators.getInstantiatorFor(entity)).isEqualTo(customInstantiator);
|
||||
|
||||
when(entity.getType()).thenReturn((Class) String.class);
|
||||
assertThat(instantiators.getInstantiatorFor(entity), is((EntityInstantiator) ReflectionEntityInstantiator.INSTANCE));
|
||||
doReturn(String.class).when(entity).getType();
|
||||
assertThat(instantiators.getInstantiatorFor(entity))
|
||||
.isEqualTo((EntityInstantiator) ReflectionEntityInstantiator.INSTANCE);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.convert;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Duration;
|
||||
@@ -76,53 +75,54 @@ public class Jsr310ConvertersUnitTests {
|
||||
|
||||
@Test // DATACMNS-606
|
||||
public void convertsDateToLocalDateTime() {
|
||||
assertThat(CONVERSION_SERVICE.convert(NOW, LocalDateTime.class).toString(),
|
||||
is(format(NOW, "yyyy-MM-dd'T'HH:mm:ss.SSS")));
|
||||
assertThat(CONVERSION_SERVICE.convert(NOW, LocalDateTime.class).toString())
|
||||
.isEqualTo(format(NOW, "yyyy-MM-dd'T'HH:mm:ss.SSS"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-606
|
||||
public void convertsLocalDateTimeToDate() {
|
||||
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
assertThat(format(CONVERSION_SERVICE.convert(now, Date.class), "yyyy-MM-dd'T'HH:mm:ss.SSS"), is(now.toString()));
|
||||
assertThat(format(CONVERSION_SERVICE.convert(now, Date.class), "yyyy-MM-dd'T'HH:mm:ss.SSS"))
|
||||
.isEqualTo(now.toString());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-606
|
||||
public void convertsDateToLocalDate() {
|
||||
assertThat(CONVERSION_SERVICE.convert(NOW, LocalDate.class).toString(), is(format(NOW, "yyyy-MM-dd")));
|
||||
assertThat(CONVERSION_SERVICE.convert(NOW, LocalDate.class).toString()).isEqualTo(format(NOW, "yyyy-MM-dd"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-606
|
||||
public void convertsLocalDateToDate() {
|
||||
|
||||
LocalDate now = LocalDate.now();
|
||||
assertThat(format(CONVERSION_SERVICE.convert(now, Date.class), "yyyy-MM-dd"), is(now.toString()));
|
||||
assertThat(format(CONVERSION_SERVICE.convert(now, Date.class), "yyyy-MM-dd")).isEqualTo(now.toString());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-606
|
||||
public void convertsDateToLocalTime() {
|
||||
assertThat(CONVERSION_SERVICE.convert(NOW, LocalTime.class).toString(), is(format(NOW, "HH:mm:ss.SSS")));
|
||||
assertThat(CONVERSION_SERVICE.convert(NOW, LocalTime.class).toString()).isEqualTo(format(NOW, "HH:mm:ss.SSS"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-606
|
||||
public void convertsLocalTimeToDate() {
|
||||
|
||||
LocalTime now = LocalTime.now();
|
||||
assertThat(format(CONVERSION_SERVICE.convert(now, Date.class), "HH:mm:ss.SSS"), is(now.toString()));
|
||||
assertThat(format(CONVERSION_SERVICE.convert(now, Date.class), "HH:mm:ss.SSS")).isEqualTo(now.toString());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-623
|
||||
public void convertsDateToInstant() {
|
||||
|
||||
Date now = new Date();
|
||||
assertThat(CONVERSION_SERVICE.convert(now, Instant.class), is(now.toInstant()));
|
||||
assertThat(CONVERSION_SERVICE.convert(now, Instant.class)).isEqualTo(now.toInstant());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-623
|
||||
public void convertsInstantToDate() {
|
||||
|
||||
Date now = new Date();
|
||||
assertThat(CONVERSION_SERVICE.convert(now.toInstant(), Date.class), is(now));
|
||||
assertThat(CONVERSION_SERVICE.convert(now.toInstant(), Date.class)).isEqualTo(now);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -133,8 +133,8 @@ public class Jsr310ConvertersUnitTests {
|
||||
ids.put("+06:00", ZoneId.of("+06:00"));
|
||||
|
||||
for (Entry<String, ZoneId> entry : ids.entrySet()) {
|
||||
assertThat(CONVERSION_SERVICE.convert(entry.getValue(), String.class), is(entry.getKey()));
|
||||
assertThat(CONVERSION_SERVICE.convert(entry.getKey(), ZoneId.class), is(entry.getValue()));
|
||||
assertThat(CONVERSION_SERVICE.convert(entry.getValue(), String.class)).isEqualTo(entry.getKey());
|
||||
assertThat(CONVERSION_SERVICE.convert(entry.getKey(), ZoneId.class)).isEqualTo(entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,8 +186,8 @@ public class Jsr310ConvertersUnitTests {
|
||||
public void convertsPeriodToStringAndBack() {
|
||||
|
||||
ResolvableType type = ResolvableType.forClass(ConversionTest.class, this.getClass());
|
||||
assertThat(CONVERSION_SERVICE.convert(target, String.class), is(string));
|
||||
assertThat(CONVERSION_SERVICE.convert(string, type.getGeneric(0).getRawClass()), is((Object) target));
|
||||
assertThat(CONVERSION_SERVICE.convert(target, String.class)).isEqualTo(string);
|
||||
assertThat(CONVERSION_SERVICE.convert(string, type.getGeneric(0).getRawClass())).isEqualTo(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
15
src/test/java/org/springframework/data/convert/MappingContextTypeInformationMapperUnitTests.java
Normal file → Executable file
15
src/test/java/org/springframework/data/convert/MappingContextTypeInformationMapperUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.convert;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.util.ClassTypeInformation.*;
|
||||
|
||||
import java.util.Collections;
|
||||
@@ -59,7 +58,7 @@ public class MappingContextTypeInformationMapperUnitTests {
|
||||
|
||||
mapper = new MappingContextTypeInformationMapper(mappingContext);
|
||||
|
||||
assertThat(mapper.createAliasFor(ClassTypeInformation.from(Entity.class)), is((Object) "foo"));
|
||||
assertThat(mapper.createAliasFor(ClassTypeInformation.from(Entity.class))).isEqualTo("foo");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -70,7 +69,7 @@ public class MappingContextTypeInformationMapperUnitTests {
|
||||
|
||||
mapper = new MappingContextTypeInformationMapper(mappingContext);
|
||||
|
||||
assertThat(mapper.createAliasFor(from(Entity.class)), is((Object) "foo"));
|
||||
assertThat(mapper.createAliasFor(from(Entity.class))).isEqualTo("foo");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -80,7 +79,7 @@ public class MappingContextTypeInformationMapperUnitTests {
|
||||
mappingContext.initialize();
|
||||
|
||||
mapper = new MappingContextTypeInformationMapper(mappingContext);
|
||||
assertThat(mapper.createAliasFor(from(String.class)), is(nullValue()));
|
||||
assertThat(mapper.createAliasFor(from(String.class))).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -91,12 +90,12 @@ public class MappingContextTypeInformationMapperUnitTests {
|
||||
mappingContext.initialize();
|
||||
|
||||
mapper = new MappingContextTypeInformationMapper(mappingContext);
|
||||
assertThat(mapper.resolveTypeFrom("foo"), is(nullValue()));
|
||||
assertThat(mapper.resolveTypeFrom("foo")).isNull();
|
||||
|
||||
PersistentEntity<?, SamplePersistentProperty> entity = mappingContext.getPersistentEntity(Entity.class);
|
||||
|
||||
assertThat(entity, is(notNullValue()));
|
||||
assertThat(mapper.resolveTypeFrom("foo"), is((TypeInformation) from(Entity.class)));
|
||||
assertThat(entity).isNotNull();
|
||||
assertThat(mapper.resolveTypeFrom("foo")).isEqualTo((TypeInformation) from(Entity.class));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-485
|
||||
|
||||
91
src/test/java/org/springframework/data/convert/ReflectionEntityInstantiatorUnitTests.java
Normal file → Executable file
91
src/test/java/org/springframework/data/convert/ReflectionEntityInstantiatorUnitTests.java
Normal file → Executable file
@@ -15,21 +15,21 @@
|
||||
*/
|
||||
package org.springframework.data.convert;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.data.convert.ReflectionEntityInstantiator.*;
|
||||
import static org.springframework.data.util.ClassTypeInformation.*;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.convert.ReflectionEntityInstantiatorUnitTests.Outer.Inner;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
@@ -41,7 +41,6 @@ import org.springframework.data.mapping.model.MappingInstantiationException;
|
||||
import org.springframework.data.mapping.model.ParameterValueProvider;
|
||||
import org.springframework.data.mapping.model.PreferredConstructorDiscoverer;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springframework.util.ReflectionUtils.FieldCallback;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link ReflectionEntityInstantiator}.
|
||||
@@ -52,52 +51,54 @@ import org.springframework.util.ReflectionUtils.FieldCallback;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ReflectionEntityInstantiatorUnitTests<P extends PersistentProperty<P>> {
|
||||
|
||||
@Mock
|
||||
PersistentEntity<?, P> entity;
|
||||
@Mock
|
||||
ParameterValueProvider<P> provider;
|
||||
@Mock
|
||||
PreferredConstructor<?, P> constructor;
|
||||
@Mock
|
||||
Parameter<?, P> parameter;
|
||||
@Mock PersistentEntity<?, P> entity;
|
||||
@Mock ParameterValueProvider<P> provider;
|
||||
@Mock PreferredConstructor<?, P> constructor;
|
||||
@Mock Parameter<?, P> parameter;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
doReturn(Optional.empty()).when(entity).getPersistenceConstructor();
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiatesSimpleObjectCorrectly() {
|
||||
|
||||
when(entity.getType()).thenReturn((Class) Object.class);
|
||||
doReturn(Object.class).when(entity).getType();
|
||||
INSTANCE.createInstance(entity, provider);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiatesArrayCorrectly() {
|
||||
|
||||
when(entity.getType()).thenReturn((Class) String[][].class);
|
||||
doReturn(String[][].class).when(entity).getType();
|
||||
INSTANCE.createInstance(entity, provider);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void instantiatesTypeWithPreferredConstructorUsingParameterValueProvider() {
|
||||
|
||||
PreferredConstructor constructor = new PreferredConstructorDiscoverer<Foo, P>(Foo.class).getConstructor();
|
||||
Optional<? extends PreferredConstructor<Foo, P>> constructor = new PreferredConstructorDiscoverer<Foo, P>(Foo.class)
|
||||
.getConstructor();
|
||||
|
||||
when(entity.getType()).thenReturn((Class) Foo.class);
|
||||
when(entity.getPersistenceConstructor()).thenReturn(constructor);
|
||||
doReturn(Foo.class).when(entity).getType();
|
||||
doReturn(constructor).when(entity).getPersistenceConstructor();
|
||||
doReturn(Optional.empty()).when(provider).getParameterValue(any());
|
||||
|
||||
Object instance = INSTANCE.createInstance(entity, provider);
|
||||
|
||||
assertTrue(instance instanceof Foo);
|
||||
verify(provider, times(1)).getParameterValue((Parameter) constructor.getParameters().iterator().next());
|
||||
assertThat(instance).isInstanceOf(Foo.class);
|
||||
assertThat(constructor).hasValueSatisfying(it -> {
|
||||
verify(provider, times(1)).getParameterValue(it.getParameters().iterator().next());
|
||||
});
|
||||
}
|
||||
|
||||
@Test(expected = MappingInstantiationException.class) // DATACMNS-300
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void throwsExceptionOnBeanInstantiationException() {
|
||||
|
||||
when(entity.getPersistenceConstructor()).thenReturn(null);
|
||||
when(entity.getType()).thenReturn((Class) PersistentEntity.class);
|
||||
doReturn(Optional.empty()).when(entity).getPersistenceConstructor();
|
||||
doReturn(PersistentEntity.class).when(entity).getType();
|
||||
|
||||
INSTANCE.createInstance(entity, provider);
|
||||
}
|
||||
@@ -106,24 +107,24 @@ public class ReflectionEntityInstantiatorUnitTests<P extends PersistentProperty<
|
||||
public void createsInnerClassInstanceCorrectly() {
|
||||
|
||||
BasicPersistentEntity<Inner, P> entity = new BasicPersistentEntity<Inner, P>(from(Inner.class));
|
||||
PreferredConstructor<Inner, P> constructor = entity.getPersistenceConstructor();
|
||||
Parameter<Object, P> parameter = constructor.getParameters().iterator().next();
|
||||
assertThat(entity.getPersistenceConstructor()).hasValueSatisfying(it -> {
|
||||
|
||||
final Object outer = new Outer();
|
||||
Parameter<Object, P> parameter = it.getParameters().iterator().next();
|
||||
|
||||
when(provider.getParameterValue(parameter)).thenReturn(outer);
|
||||
final Inner instance = INSTANCE.createInstance(entity, provider);
|
||||
Object outer = new Outer();
|
||||
|
||||
assertThat(instance, is(notNullValue()));
|
||||
when(provider.getParameterValue(parameter)).thenReturn(Optional.of(outer));
|
||||
Inner instance = INSTANCE.createInstance(entity, provider);
|
||||
|
||||
// Hack to check syntheic field as compiles create different field names (e.g. this$0, this$1)
|
||||
ReflectionUtils.doWithFields(Inner.class, new FieldCallback() {
|
||||
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
|
||||
assertThat(instance).isNotNull();
|
||||
|
||||
// Hack to check synthetic field as compiles create different field names (e.g. this$0, this$1)
|
||||
ReflectionUtils.doWithFields(Inner.class, field -> {
|
||||
if (field.isSynthetic() && field.getName().startsWith("this$")) {
|
||||
ReflectionUtils.makeAccessible(field);
|
||||
assertThat(ReflectionUtils.getField(field, instance), is(outer));
|
||||
assertThat(ReflectionUtils.getField(field, instance)).isEqualTo(outer);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -133,10 +134,10 @@ public class ReflectionEntityInstantiatorUnitTests<P extends PersistentProperty<
|
||||
|
||||
PersistentEntity<Sample, P> entity = new BasicPersistentEntity<Sample, P>(from(Sample.class));
|
||||
|
||||
when(provider.getParameterValue(Mockito.any(Parameter.class))).thenReturn("FOO");
|
||||
doReturn(Optional.of("FOO")).when(provider).getParameterValue(any(Parameter.class));
|
||||
|
||||
Constructor constructor = Sample.class.getConstructor(Long.class, String.class);
|
||||
List<Object> parameters = Arrays.asList((Object) "FOO", (Object) "FOO");
|
||||
List<Object> parameters = Arrays.asList("FOO", "FOO");
|
||||
|
||||
try {
|
||||
|
||||
@@ -145,14 +146,14 @@ public class ReflectionEntityInstantiatorUnitTests<P extends PersistentProperty<
|
||||
|
||||
} catch (MappingInstantiationException o_O) {
|
||||
|
||||
assertThat(o_O.getConstructor(), is(constructor));
|
||||
assertThat(o_O.getConstructorArguments(), is(parameters));
|
||||
assertEquals(Sample.class, o_O.getEntityType());
|
||||
assertThat(o_O.getConstructor()).hasValue(constructor);
|
||||
assertThat(o_O.getConstructorArguments()).isEqualTo(parameters);
|
||||
assertThat(o_O.getEntityType()).hasValue(Sample.class);
|
||||
|
||||
assertThat(o_O.getMessage(), containsString(Sample.class.getName()));
|
||||
assertThat(o_O.getMessage(), containsString(Long.class.getName()));
|
||||
assertThat(o_O.getMessage(), containsString(String.class.getName()));
|
||||
assertThat(o_O.getMessage(), containsString("FOO"));
|
||||
assertThat(o_O.getMessage()).contains(Sample.class.getName());
|
||||
assertThat(o_O.getMessage()).contains(Long.class.getName());
|
||||
assertThat(o_O.getMessage()).contains(String.class.getName());
|
||||
assertThat(o_O.getMessage()).contains("FOO");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
15
src/test/java/org/springframework/data/convert/SimpleTypeInformationMapperUnitTests.java
Normal file → Executable file
15
src/test/java/org/springframework/data/convert/SimpleTypeInformationMapperUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.convert;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
@@ -38,28 +37,28 @@ public class SimpleTypeInformationMapperUnitTests {
|
||||
|
||||
TypeInformation expected = ClassTypeInformation.from(String.class);
|
||||
|
||||
assertThat(type, is(expected));
|
||||
assertThat(type).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsNullForNonStringKey() {
|
||||
|
||||
TypeInformationMapper mapper = new SimpleTypeInformationMapper();
|
||||
assertThat(mapper.resolveTypeFrom(new Object()), is(nullValue()));
|
||||
assertThat(mapper.resolveTypeFrom(new Object())).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsNullForEmptyTypeKey() {
|
||||
|
||||
TypeInformationMapper mapper = new SimpleTypeInformationMapper();
|
||||
assertThat(mapper.resolveTypeFrom(""), is(nullValue()));
|
||||
assertThat(mapper.resolveTypeFrom("")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsNullForUnloadableClass() {
|
||||
|
||||
TypeInformationMapper mapper = new SimpleTypeInformationMapper();
|
||||
assertThat(mapper.resolveTypeFrom("Foo"), is(nullValue()));
|
||||
assertThat(mapper.resolveTypeFrom("Foo")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -68,7 +67,7 @@ public class SimpleTypeInformationMapperUnitTests {
|
||||
TypeInformationMapper mapper = new SimpleTypeInformationMapper();
|
||||
Object alias = mapper.createAliasFor(ClassTypeInformation.from(String.class));
|
||||
|
||||
assertTrue(alias instanceof String);
|
||||
assertThat(alias, is((Object) String.class.getName()));
|
||||
assertThat(alias).isInstanceOf(String.class);
|
||||
assertThat(alias).isEqualTo(String.class.getName());
|
||||
}
|
||||
}
|
||||
|
||||
26
src/test/java/org/springframework/data/convert/ThreeTenBackPortConvertersUnitTests.java
Normal file → Executable file
26
src/test/java/org/springframework/data/convert/ThreeTenBackPortConvertersUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.convert;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.threeten.bp.DateTimeUtils.*;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
@@ -59,53 +58,54 @@ public class ThreeTenBackPortConvertersUnitTests {
|
||||
|
||||
@Test // DATACMNS-606
|
||||
public void convertsDateToLocalDateTime() {
|
||||
assertThat(CONVERSION_SERVICE.convert(NOW, LocalDateTime.class).toString(),
|
||||
is(format(NOW, "yyyy-MM-dd'T'HH:mm:ss.SSS")));
|
||||
assertThat(CONVERSION_SERVICE.convert(NOW, LocalDateTime.class).toString())
|
||||
.isEqualTo(format(NOW, "yyyy-MM-dd'T'HH:mm:ss.SSS"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-606
|
||||
public void convertsLocalDateTimeToDate() {
|
||||
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
assertThat(format(CONVERSION_SERVICE.convert(now, Date.class), "yyyy-MM-dd'T'HH:mm:ss.SSS"), is(now.toString()));
|
||||
assertThat(format(CONVERSION_SERVICE.convert(now, Date.class), "yyyy-MM-dd'T'HH:mm:ss.SSS"))
|
||||
.isEqualTo(now.toString());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-606
|
||||
public void convertsDateToLocalDate() {
|
||||
assertThat(CONVERSION_SERVICE.convert(NOW, LocalDate.class).toString(), is(format(NOW, "yyyy-MM-dd")));
|
||||
assertThat(CONVERSION_SERVICE.convert(NOW, LocalDate.class).toString()).isEqualTo(format(NOW, "yyyy-MM-dd"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-606
|
||||
public void convertsLocalDateToDate() {
|
||||
|
||||
LocalDate now = LocalDate.now();
|
||||
assertThat(format(CONVERSION_SERVICE.convert(now, Date.class), "yyyy-MM-dd"), is(now.toString()));
|
||||
assertThat(format(CONVERSION_SERVICE.convert(now, Date.class), "yyyy-MM-dd")).isEqualTo(now.toString());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-606
|
||||
public void convertsDateToLocalTime() {
|
||||
assertThat(CONVERSION_SERVICE.convert(NOW, LocalTime.class).toString(), is(format(NOW, "HH:mm:ss.SSS")));
|
||||
assertThat(CONVERSION_SERVICE.convert(NOW, LocalTime.class).toString()).isEqualTo(format(NOW, "HH:mm:ss.SSS"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-606
|
||||
public void convertsLocalTimeToDate() {
|
||||
|
||||
LocalTime now = LocalTime.now();
|
||||
assertThat(format(CONVERSION_SERVICE.convert(now, Date.class), "HH:mm:ss.SSS"), is(now.toString()));
|
||||
assertThat(format(CONVERSION_SERVICE.convert(now, Date.class), "HH:mm:ss.SSS")).isEqualTo(now.toString());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-623
|
||||
public void convertsDateToInstant() {
|
||||
|
||||
Date now = new Date();
|
||||
assertThat(CONVERSION_SERVICE.convert(now, Instant.class), is(toInstant(now)));
|
||||
assertThat(CONVERSION_SERVICE.convert(now, Instant.class)).isEqualTo(toInstant(now));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-623
|
||||
public void convertsInstantToDate() {
|
||||
|
||||
Date now = new Date();
|
||||
assertThat(CONVERSION_SERVICE.convert(toInstant(now), Date.class), is(now));
|
||||
assertThat(CONVERSION_SERVICE.convert(toInstant(now), Date.class)).isEqualTo(now);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -116,8 +116,8 @@ public class ThreeTenBackPortConvertersUnitTests {
|
||||
ids.put("+06:00", ZoneId.of("+06:00"));
|
||||
|
||||
for (Entry<String, ZoneId> entry : ids.entrySet()) {
|
||||
assertThat(CONVERSION_SERVICE.convert(entry.getValue(), String.class), is(entry.getKey()));
|
||||
assertThat(CONVERSION_SERVICE.convert(entry.getKey(), ZoneId.class), is(entry.getValue()));
|
||||
assertThat(CONVERSION_SERVICE.convert(entry.getValue(), String.class)).isEqualTo(entry.getKey());
|
||||
assertThat(CONVERSION_SERVICE.convert(entry.getKey(), ZoneId.class)).isEqualTo(entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
15
src/test/java/org/springframework/data/domain/AbstractPageRequestUnitTests.java
Normal file → Executable file
15
src/test/java/org/springframework/data/domain/AbstractPageRequestUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.domain;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.domain.UnitTestUtils.*;
|
||||
|
||||
import org.junit.Test;
|
||||
@@ -43,15 +42,15 @@ public abstract class AbstractPageRequestUnitTests {
|
||||
|
||||
Pageable request = newPageRequest(1, 10);
|
||||
|
||||
assertThat(request.hasPrevious(), is(true));
|
||||
assertThat(request.next(), is((Pageable) newPageRequest(2, 10)));
|
||||
assertThat(request.hasPrevious()).isTrue();
|
||||
assertThat(request.next()).isEqualTo((Pageable) newPageRequest(2, 10));
|
||||
|
||||
Pageable first = request.previousOrFirst();
|
||||
|
||||
assertThat(first.hasPrevious(), is(false));
|
||||
assertThat(first, is((Pageable) newPageRequest(0, 10)));
|
||||
assertThat(first, is(request.first()));
|
||||
assertThat(first.previousOrFirst(), is(first));
|
||||
assertThat(first.hasPrevious()).isFalse();
|
||||
assertThat(first).isEqualTo((Pageable) newPageRequest(0, 10));
|
||||
assertThat(first).isEqualTo(request.first());
|
||||
assertThat(first.previousOrFirst()).isEqualTo(first);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
7
src/test/java/org/springframework/data/domain/DirectionUnitTests.java
Normal file → Executable file
7
src/test/java/org/springframework/data/domain/DirectionUnitTests.java
Normal file → Executable file
@@ -1,6 +1,6 @@
|
||||
package org.springframework.data.domain;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
@@ -15,13 +15,12 @@ public class DirectionUnitTests {
|
||||
@Test
|
||||
public void jpaValueMapping() throws Exception {
|
||||
|
||||
assertEquals(Direction.ASC, Direction.fromString("asc"));
|
||||
assertEquals(Direction.DESC, Direction.fromString("desc"));
|
||||
assertThat(Direction.fromString("asc")).isEqualTo(Direction.ASC);
|
||||
assertThat(Direction.fromString("desc")).isEqualTo(Direction.DESC);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsInvalidString() throws Exception {
|
||||
|
||||
Direction.fromString("foo");
|
||||
}
|
||||
}
|
||||
|
||||
65
src/test/java/org/springframework/data/domain/ExampleMatcherUnitTests.java
Normal file → Executable file
65
src/test/java/org/springframework/data/domain/ExampleMatcherUnitTests.java
Normal file → Executable file
@@ -15,14 +15,17 @@
|
||||
*/
|
||||
package org.springframework.data.domain;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.springframework.data.domain.ExampleMatcher.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.ExampleMatcher.*;
|
||||
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatcher;
|
||||
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers;
|
||||
import org.springframework.data.domain.ExampleMatcher.MatcherConfigurer;
|
||||
import org.springframework.data.domain.ExampleMatcher.NullHandler;
|
||||
import org.springframework.data.domain.ExampleMatcher.StringMatcher;
|
||||
|
||||
/**
|
||||
* Unit test for {@link ExampleMatcher}.
|
||||
@@ -42,22 +45,22 @@ public class ExampleMatcherUnitTests {
|
||||
|
||||
@Test // DATACMNS-810
|
||||
public void defaultStringMatcherShouldReturnDefault() throws Exception {
|
||||
assertThat(matcher.getDefaultStringMatcher(), is(StringMatcher.DEFAULT));
|
||||
assertThat(matcher.getDefaultStringMatcher()).isEqualTo(StringMatcher.DEFAULT);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-810
|
||||
public void ignoreCaseShouldReturnFalseByDefault() throws Exception {
|
||||
assertThat(matcher.isIgnoreCaseEnabled(), is(false));
|
||||
assertThat(matcher.isIgnoreCaseEnabled()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-810
|
||||
public void ignoredPathsIsEmptyByDefault() throws Exception {
|
||||
assertThat(matcher.getIgnoredPaths(), is(empty()));
|
||||
assertThat(matcher.getIgnoredPaths()).isEmpty();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-810
|
||||
public void nullHandlerShouldReturnIgnoreByDefault() throws Exception {
|
||||
assertThat(matcher.getNullHandler(), is(NullHandler.IGNORE));
|
||||
assertThat(matcher.getNullHandler()).isEqualTo(NullHandler.IGNORE);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class) // DATACMNS-810
|
||||
@@ -70,7 +73,7 @@ public class ExampleMatcherUnitTests {
|
||||
|
||||
matcher = matching().withIgnoreCase();
|
||||
|
||||
assertThat(matcher.isIgnoreCaseEnabled(), is(true));
|
||||
assertThat(matcher.isIgnoreCaseEnabled()).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-810
|
||||
@@ -78,7 +81,7 @@ public class ExampleMatcherUnitTests {
|
||||
|
||||
matcher = matching().withIgnoreCase(true);
|
||||
|
||||
assertThat(matcher.isIgnoreCaseEnabled(), is(true));
|
||||
assertThat(matcher.isIgnoreCaseEnabled()).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-810
|
||||
@@ -86,7 +89,7 @@ public class ExampleMatcherUnitTests {
|
||||
|
||||
matcher = matching().withIncludeNullValues();
|
||||
|
||||
assertThat(matcher.getNullHandler(), is(NullHandler.INCLUDE));
|
||||
assertThat(matcher.getNullHandler()).isEqualTo(NullHandler.INCLUDE);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-810
|
||||
@@ -94,7 +97,7 @@ public class ExampleMatcherUnitTests {
|
||||
|
||||
matcher = matching().withIgnoreNullValues();
|
||||
|
||||
assertThat(matcher.getNullHandler(), is(NullHandler.IGNORE));
|
||||
assertThat(matcher.getNullHandler()).isEqualTo(NullHandler.IGNORE);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-810
|
||||
@@ -102,7 +105,7 @@ public class ExampleMatcherUnitTests {
|
||||
|
||||
matcher = matching().withNullHandler(NullHandler.INCLUDE);
|
||||
|
||||
assertThat(matcher.getNullHandler(), is(NullHandler.INCLUDE));
|
||||
assertThat(matcher.getNullHandler()).isEqualTo(NullHandler.INCLUDE);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-810
|
||||
@@ -110,8 +113,8 @@ public class ExampleMatcherUnitTests {
|
||||
|
||||
matcher = matching().withIgnorePaths("foo", "bar", "baz");
|
||||
|
||||
assertThat(matcher.getIgnoredPaths(), contains("foo", "bar", "baz"));
|
||||
assertThat(matcher.getIgnoredPaths(), hasSize(3));
|
||||
assertThat(matcher.getIgnoredPaths()).contains("foo", "bar", "baz");
|
||||
assertThat(matcher.getIgnoredPaths()).hasSize(3);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-810
|
||||
@@ -119,8 +122,8 @@ public class ExampleMatcherUnitTests {
|
||||
|
||||
matcher = matching().withIgnorePaths("foo", "bar", "foo");
|
||||
|
||||
assertThat(matcher.getIgnoredPaths(), contains("foo", "bar"));
|
||||
assertThat(matcher.getIgnoredPaths(), hasSize(2));
|
||||
assertThat(matcher.getIgnoredPaths()).contains("foo", "bar");
|
||||
assertThat(matcher.getIgnoredPaths()).hasSize(2);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-810
|
||||
@@ -129,33 +132,33 @@ public class ExampleMatcherUnitTests {
|
||||
matcher = matching().withIgnorePaths("foo", "bar", "foo");
|
||||
ExampleMatcher configuredExampleSpec = matcher.withIgnoreCase();
|
||||
|
||||
assertThat(matcher, is(not(sameInstance(configuredExampleSpec))));
|
||||
assertThat(matcher.getIgnoredPaths(), hasSize(2));
|
||||
assertThat(matcher.isIgnoreCaseEnabled(), is(false));
|
||||
assertThat(matcher).isNotEqualTo(sameInstance(configuredExampleSpec));
|
||||
assertThat(matcher.getIgnoredPaths()).hasSize(2);
|
||||
assertThat(matcher.isIgnoreCaseEnabled()).isFalse();
|
||||
|
||||
assertThat(configuredExampleSpec.getIgnoredPaths(), hasSize(2));
|
||||
assertThat(configuredExampleSpec.isIgnoreCaseEnabled(), is(true));
|
||||
assertThat(configuredExampleSpec.getIgnoredPaths()).hasSize(2);
|
||||
assertThat(configuredExampleSpec.isIgnoreCaseEnabled()).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-879
|
||||
public void defaultMatcherRequiresAllMatching() {
|
||||
|
||||
assertThat(matching().isAllMatching(), is(true));
|
||||
assertThat(matching().isAnyMatching(), is(false));
|
||||
assertThat(matching().isAllMatching()).isTrue();
|
||||
assertThat(matching().isAnyMatching()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-879
|
||||
public void allMatcherRequiresAllMatching() {
|
||||
|
||||
assertThat(matchingAll().isAllMatching(), is(true));
|
||||
assertThat(matchingAll().isAnyMatching(), is(false));
|
||||
assertThat(matchingAll().isAllMatching()).isTrue();
|
||||
assertThat(matchingAll().isAnyMatching()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-879
|
||||
public void anyMatcherYieldsAnyMatching() {
|
||||
|
||||
assertThat(matchingAny().isAnyMatching(), is(true));
|
||||
assertThat(matchingAny().isAllMatching(), is(false));
|
||||
assertThat(matchingAny().isAnyMatching()).isTrue();
|
||||
assertThat(matchingAny().isAllMatching()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-900
|
||||
@@ -190,10 +193,10 @@ public class ExampleMatcherUnitTests {
|
||||
.withNullHandler(NullHandler.IGNORE) //
|
||||
.withMatcher("hello", GenericPropertyMatchers.contains().ignoreCase());
|
||||
|
||||
assertThat(matcher.hashCode(), is(sameAsMatcher.hashCode()));
|
||||
assertThat(matcher.hashCode(), is(not(different.hashCode())));
|
||||
assertThat(matcher, is(equalTo(sameAsMatcher)));
|
||||
assertThat(matcher, is(not(equalTo(different))));
|
||||
assertThat(matcher.hashCode()).isEqualTo(sameAsMatcher.hashCode());
|
||||
assertThat(matcher.hashCode()).isNotEqualTo(different.hashCode());
|
||||
assertThat(matcher).isEqualTo(sameAsMatcher);
|
||||
assertThat(matcher).isNotEqualTo(different);
|
||||
}
|
||||
|
||||
static class Person {
|
||||
|
||||
17
src/test/java/org/springframework/data/domain/ExampleUnitTests.java
Normal file → Executable file
17
src/test/java/org/springframework/data/domain/ExampleUnitTests.java
Normal file → Executable file
@@ -15,13 +15,12 @@
|
||||
*/
|
||||
package org.springframework.data.domain;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.domain.ExampleMatcher.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.ExampleMatcher.*;
|
||||
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers;
|
||||
|
||||
/**
|
||||
* Test for {@link Example}.
|
||||
@@ -50,8 +49,8 @@ public class ExampleUnitTests {
|
||||
}
|
||||
|
||||
@Test // DATACMNS-810
|
||||
public void returnsSampleObjectsClassAsProbeType() {
|
||||
assertThat(example.getProbeType(), is(equalTo(Person.class)));
|
||||
public void retunsSampleObjectsClassAsProbeType() {
|
||||
assertThat(example.getProbeType()).isEqualTo(Person.class);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-900
|
||||
@@ -63,10 +62,10 @@ public class ExampleUnitTests {
|
||||
Example<Person> different = Example.of(person,
|
||||
matching().withMatcher("firstname", GenericPropertyMatchers.contains()));
|
||||
|
||||
assertThat(example.hashCode(), is(sameAsExample.hashCode()));
|
||||
assertThat(example.hashCode(), is(not(different.hashCode())));
|
||||
assertThat(example, is(equalTo(sameAsExample)));
|
||||
assertThat(example, is(not(equalTo(different))));
|
||||
assertThat(example.hashCode()).isEqualTo(sameAsExample.hashCode());
|
||||
assertThat(example.hashCode()).isNotEqualTo(different.hashCode());
|
||||
assertThat(example).isEqualTo(sameAsExample);
|
||||
assertThat(example).isNotEqualTo(different);
|
||||
}
|
||||
|
||||
static class Person {
|
||||
|
||||
79
src/test/java/org/springframework/data/domain/PageImplUnitTests.java
Normal file → Executable file
79
src/test/java/org/springframework/data/domain/PageImplUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.domain;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.domain.UnitTestUtils.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
@@ -72,13 +71,13 @@ public class PageImplUnitTests {
|
||||
|
||||
Page<Object> page = new PageImpl<Object>(Arrays.asList(new Object()), new PageRequest(0, 1), 10);
|
||||
|
||||
assertThat(page.isFirst(), is(true));
|
||||
assertThat(page.hasPrevious(), is(false));
|
||||
assertThat(page.previousPageable(), is(nullValue()));
|
||||
assertThat(page.isFirst()).isTrue();
|
||||
assertThat(page.hasPrevious()).isFalse();
|
||||
assertThat(page.previousPageable()).isNull();
|
||||
|
||||
assertThat(page.isLast(), is(false));
|
||||
assertThat(page.hasNext(), is(true));
|
||||
assertThat(page.nextPageable(), is((Pageable) new PageRequest(1, 1)));
|
||||
assertThat(page.isLast()).isFalse();
|
||||
assertThat(page.hasNext()).isTrue();
|
||||
assertThat(page.nextPageable()).isEqualTo((Pageable) new PageRequest(1, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -86,13 +85,13 @@ public class PageImplUnitTests {
|
||||
|
||||
Page<Object> page = new PageImpl<Object>(Arrays.asList(new Object()), new PageRequest(1, 1), 2);
|
||||
|
||||
assertThat(page.isFirst(), is(false));
|
||||
assertThat(page.hasPrevious(), is(true));
|
||||
assertThat(page.previousPageable(), is((Pageable) new PageRequest(0, 1)));
|
||||
assertThat(page.isFirst()).isFalse();
|
||||
assertThat(page.hasPrevious()).isTrue();
|
||||
assertThat(page.previousPageable()).isEqualTo((Pageable) new PageRequest(0, 1));
|
||||
|
||||
assertThat(page.isLast(), is(true));
|
||||
assertThat(page.hasNext(), is(false));
|
||||
assertThat(page.nextPageable(), is(nullValue()));
|
||||
assertThat(page.isLast()).isTrue();
|
||||
assertThat(page.hasNext()).isFalse();
|
||||
assertThat(page.nextPageable()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -101,18 +100,18 @@ public class PageImplUnitTests {
|
||||
List<String> list = Collections.emptyList();
|
||||
Page<String> page = new PageImpl<String>(list);
|
||||
|
||||
assertThat(page.getContent(), is(list));
|
||||
assertThat(page.getNumber(), is(0));
|
||||
assertThat(page.getNumberOfElements(), is(0));
|
||||
assertThat(page.getSize(), is(0));
|
||||
assertThat(page.getSort(), is((Sort) null));
|
||||
assertThat(page.getTotalElements(), is(0L));
|
||||
assertThat(page.getTotalPages(), is(1));
|
||||
assertThat(page.hasNext(), is(false));
|
||||
assertThat(page.hasPrevious(), is(false));
|
||||
assertThat(page.isFirst(), is(true));
|
||||
assertThat(page.isLast(), is(true));
|
||||
assertThat(page.hasContent(), is(false));
|
||||
assertThat(page.getContent()).isEqualTo(list);
|
||||
assertThat(page.getNumber()).isEqualTo(0);
|
||||
assertThat(page.getNumberOfElements()).isEqualTo(0);
|
||||
assertThat(page.getSize()).isEqualTo(0);
|
||||
assertThat(page.getSort()).isEqualTo((Sort) null);
|
||||
assertThat(page.getTotalElements()).isEqualTo(0L);
|
||||
assertThat(page.getTotalPages()).isEqualTo(1);
|
||||
assertThat(page.hasNext()).isFalse();
|
||||
assertThat(page.hasPrevious()).isFalse();
|
||||
assertThat(page.isFirst()).isTrue();
|
||||
assertThat(page.isLast()).isTrue();
|
||||
assertThat(page.hasContent()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-323
|
||||
@@ -120,9 +119,9 @@ public class PageImplUnitTests {
|
||||
|
||||
Page<String> page = new PageImpl<String>(Arrays.asList("a"));
|
||||
|
||||
assertThat(page.getTotalPages(), is(1));
|
||||
assertThat(page.hasNext(), is(false));
|
||||
assertThat(page.hasPrevious(), is(false));
|
||||
assertThat(page.getTotalPages()).isEqualTo(1);
|
||||
assertThat(page.hasNext()).isFalse();
|
||||
assertThat(page.hasPrevious()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-635
|
||||
@@ -136,36 +135,38 @@ public class PageImplUnitTests {
|
||||
}
|
||||
});
|
||||
|
||||
assertThat(transformed.getContent(), hasSize(2));
|
||||
assertThat(transformed.getContent(), contains(3, 3));
|
||||
assertThat(transformed.getContent()).hasSize(2);
|
||||
assertThat(transformed.getContent()).contains(3, 3);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-713
|
||||
public void adaptsTotalForLastPageOnIntermediateDeletion() {
|
||||
assertThat(new PageImpl<String>(Arrays.asList("foo", "bar"), new PageRequest(0, 5), 3).getTotalElements(), is(2L));
|
||||
assertThat(new PageImpl<String>(Arrays.asList("foo", "bar"), new PageRequest(0, 5), 3).getTotalElements())
|
||||
.isEqualTo(2L);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-713
|
||||
public void adaptsTotalForLastPageOnIntermediateInsertion() {
|
||||
assertThat(new PageImpl<String>(Arrays.asList("foo", "bar"), new PageRequest(0, 5), 1).getTotalElements(), is(2L));
|
||||
assertThat(new PageImpl<String>(Arrays.asList("foo", "bar"), new PageRequest(0, 5), 1).getTotalElements())
|
||||
.isEqualTo(2L);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-713
|
||||
public void adaptsTotalForLastPageOnIntermediateDeletionOnLastPate() {
|
||||
assertThat(new PageImpl<String>(Arrays.asList("foo", "bar"), new PageRequest(1, 10), 13).getTotalElements(),
|
||||
is(12L));
|
||||
assertThat(new PageImpl<String>(Arrays.asList("foo", "bar"), new PageRequest(1, 10), 13).getTotalElements())
|
||||
.isEqualTo(12L);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-713
|
||||
public void adaptsTotalForLastPageOnIntermediateInsertionOnLastPate() {
|
||||
assertThat(new PageImpl<String>(Arrays.asList("foo", "bar"), new PageRequest(1, 10), 11).getTotalElements(),
|
||||
is(12L));
|
||||
assertThat(new PageImpl<String>(Arrays.asList("foo", "bar"), new PageRequest(1, 10), 11).getTotalElements())
|
||||
.isEqualTo(12L);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-713
|
||||
public void doesNotAdapttotalIfPageIsEmpty() {
|
||||
|
||||
assertThat(new PageImpl<String>(Collections.<String> emptyList(), new PageRequest(1, 10), 0).getTotalElements(),
|
||||
is(0L));
|
||||
assertThat(new PageImpl<String>(Collections.<String> emptyList(), new PageRequest(1, 10), 0).getTotalElements())
|
||||
.isEqualTo(0L);
|
||||
}
|
||||
}
|
||||
|
||||
0
src/test/java/org/springframework/data/domain/PageRequestUnitTests.java
Normal file → Executable file
0
src/test/java/org/springframework/data/domain/PageRequestUnitTests.java
Normal file → Executable file
53
src/test/java/org/springframework/data/domain/RangeUnitTests.java
Normal file → Executable file
53
src/test/java/org/springframework/data/domain/RangeUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.domain;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -38,11 +37,11 @@ public class RangeUnitTests {
|
||||
|
||||
Range<Long> range = new Range<Long>(10L, 20L);
|
||||
|
||||
assertThat(range.contains(10L), is(true));
|
||||
assertThat(range.contains(20L), is(true));
|
||||
assertThat(range.contains(15L), is(true));
|
||||
assertThat(range.contains(5L), is(false));
|
||||
assertThat(range.contains(25L), is(false));
|
||||
assertThat(range.contains(10L)).isTrue();
|
||||
assertThat(range.contains(20L)).isTrue();
|
||||
assertThat(range.contains(15L)).isTrue();
|
||||
assertThat(range.contains(5L)).isFalse();
|
||||
assertThat(range.contains(25L)).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-651
|
||||
@@ -50,11 +49,11 @@ public class RangeUnitTests {
|
||||
|
||||
Range<Long> range = new Range<Long>(10L, 20L, false, true);
|
||||
|
||||
assertThat(range.contains(10L), is(false));
|
||||
assertThat(range.contains(20L), is(true));
|
||||
assertThat(range.contains(15L), is(true));
|
||||
assertThat(range.contains(5L), is(false));
|
||||
assertThat(range.contains(25L), is(false));
|
||||
assertThat(range.contains(10L)).isFalse();
|
||||
assertThat(range.contains(20L)).isTrue();
|
||||
assertThat(range.contains(15L)).isTrue();
|
||||
assertThat(range.contains(5L)).isFalse();
|
||||
assertThat(range.contains(25L)).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-651
|
||||
@@ -62,11 +61,11 @@ public class RangeUnitTests {
|
||||
|
||||
Range<Long> range = new Range<Long>(10L, 20L, true, false);
|
||||
|
||||
assertThat(range.contains(10L), is(true));
|
||||
assertThat(range.contains(20L), is(false));
|
||||
assertThat(range.contains(15L), is(true));
|
||||
assertThat(range.contains(5L), is(false));
|
||||
assertThat(range.contains(25L), is(false));
|
||||
assertThat(range.contains(10L)).isTrue();
|
||||
assertThat(range.contains(20L)).isFalse();
|
||||
assertThat(range.contains(15L)).isTrue();
|
||||
assertThat(range.contains(5L)).isFalse();
|
||||
assertThat(range.contains(25L)).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-651
|
||||
@@ -74,11 +73,11 @@ public class RangeUnitTests {
|
||||
|
||||
Range<Long> range = new Range<Long>(10L, null);
|
||||
|
||||
assertThat(range.contains(10L), is(true));
|
||||
assertThat(range.contains(20L), is(true));
|
||||
assertThat(range.contains(15L), is(true));
|
||||
assertThat(range.contains(5L), is(false));
|
||||
assertThat(range.contains(25L), is(true));
|
||||
assertThat(range.contains(10L)).isTrue();
|
||||
assertThat(range.contains(20L)).isTrue();
|
||||
assertThat(range.contains(15L)).isTrue();
|
||||
assertThat(range.contains(5L)).isFalse();
|
||||
assertThat(range.contains(25L)).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-651
|
||||
@@ -86,10 +85,10 @@ public class RangeUnitTests {
|
||||
|
||||
Range<Long> range = new Range<Long>(null, 20L);
|
||||
|
||||
assertThat(range.contains(10L), is(true));
|
||||
assertThat(range.contains(20L), is(true));
|
||||
assertThat(range.contains(15L), is(true));
|
||||
assertThat(range.contains(5L), is(true));
|
||||
assertThat(range.contains(25L), is(false));
|
||||
assertThat(range.contains(10L)).isTrue();
|
||||
assertThat(range.contains(20L)).isTrue();
|
||||
assertThat(range.contains(15L)).isTrue();
|
||||
assertThat(range.contains(5L)).isTrue();
|
||||
assertThat(range.contains(25L)).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
27
src/test/java/org/springframework/data/domain/SortUnitTests.java
Normal file → Executable file
27
src/test/java/org/springframework/data/domain/SortUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.domain;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.domain.Sort.NullHandling.*;
|
||||
|
||||
import org.junit.Test;
|
||||
@@ -40,8 +39,8 @@ public class SortUnitTests {
|
||||
@Test
|
||||
public void appliesDefaultForOrder() throws Exception {
|
||||
|
||||
assertEquals(Sort.DEFAULT_DIRECTION, new Sort("foo").iterator().next().getDirection());
|
||||
assertEquals(Sort.DEFAULT_DIRECTION, new Sort((Direction) null, "foo").iterator().next().getDirection());
|
||||
assertThat(new Sort("foo").iterator().next().getDirection()).isEqualTo(Sort.DEFAULT_DIRECTION);
|
||||
assertThat(new Sort((Direction) null, "foo").iterator().next().getDirection()).isEqualTo(Sort.DEFAULT_DIRECTION);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -92,24 +91,24 @@ public class SortUnitTests {
|
||||
public void allowsCombiningSorts() {
|
||||
|
||||
Sort sort = new Sort("foo").and(new Sort("bar"));
|
||||
assertThat(sort, hasItems(new Sort.Order("foo"), new Sort.Order("bar")));
|
||||
assertThat(sort).containsExactly(new Sort.Order("foo"), new Sort.Order("bar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlesAdditionalNullSort() {
|
||||
|
||||
Sort sort = new Sort("foo").and(null);
|
||||
assertThat(sort, hasItem(new Sort.Order("foo")));
|
||||
assertThat(sort).containsExactly(new Sort.Order("foo"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-281
|
||||
public void configuresIgnoreCaseForOrder() {
|
||||
assertThat(new Order(Direction.ASC, "foo").ignoreCase().isIgnoreCase(), is(true));
|
||||
assertThat(new Order(Direction.ASC, "foo").ignoreCase().isIgnoreCase()).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-281
|
||||
public void orderDoesNotIgnoreCaseByDefault() {
|
||||
assertThat(new Order(Direction.ASC, "foo").isIgnoreCase(), is(false));
|
||||
assertThat(new Order(Direction.ASC, "foo").isIgnoreCase()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-436
|
||||
@@ -118,28 +117,28 @@ public class SortUnitTests {
|
||||
Order foo = new Order("foo");
|
||||
Order fooIgnoreCase = new Order("foo").ignoreCase();
|
||||
|
||||
assertThat(foo, is(not(fooIgnoreCase)));
|
||||
assertThat(foo.hashCode(), is(not(fooIgnoreCase.hashCode())));
|
||||
assertThat(foo).isNotEqualTo(fooIgnoreCase);
|
||||
assertThat(foo.hashCode()).isNotEqualTo(fooIgnoreCase.hashCode());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-491
|
||||
public void orderWithNullHandlingHintNullsFirst() {
|
||||
assertThat(new Order("foo").nullsFirst().getNullHandling(), is(NULLS_FIRST));
|
||||
assertThat(new Order("foo").nullsFirst().getNullHandling()).isEqualTo(NULLS_FIRST);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-491
|
||||
public void orderWithNullHandlingHintNullsLast() {
|
||||
assertThat(new Order("foo").nullsLast().getNullHandling(), is(NULLS_LAST));
|
||||
assertThat(new Order("foo").nullsLast().getNullHandling()).isEqualTo(NULLS_LAST);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-491
|
||||
public void orderWithNullHandlingHintNullsNative() {
|
||||
assertThat(new Order("foo").nullsNative().getNullHandling(), is(NATIVE));
|
||||
assertThat(new Order("foo").nullsNative().getNullHandling()).isEqualTo(NATIVE);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-491
|
||||
public void orderWithDefaultNullHandlingHint() {
|
||||
assertThat(new Order("foo").getNullHandling(), is(NATIVE));
|
||||
assertThat(new Order("foo").getNullHandling()).isEqualTo(NATIVE);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-908
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package org.springframework.data.domain;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* @author Oliver Gierke
|
||||
@@ -19,9 +19,9 @@ public abstract class UnitTestUtils {
|
||||
*/
|
||||
public static void assertEqualsAndHashcode(Object first, Object second) {
|
||||
|
||||
assertEquals(first, second);
|
||||
assertEquals(second, first);
|
||||
assertEquals(first.hashCode(), second.hashCode());
|
||||
assertThat(first).isEqualTo(second);
|
||||
assertThat(second).isEqualTo(first);
|
||||
assertThat(first.hashCode()).isEqualTo(second.hashCode());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -32,8 +32,8 @@ public abstract class UnitTestUtils {
|
||||
*/
|
||||
public static void assertNotEqualsAndHashcode(Object first, Object second) {
|
||||
|
||||
assertFalse(first.equals(second));
|
||||
assertFalse(second.equals(first));
|
||||
assertFalse(first.hashCode() == second.hashCode());
|
||||
assertThat(first).isNotEqualTo(second);
|
||||
assertThat(second).isNotEqualTo(first);
|
||||
assertThat(first.hashCode()).isNotEqualTo(second.hashCode());
|
||||
}
|
||||
}
|
||||
|
||||
11
src/test/java/org/springframework/data/domain/jaxb/SpringDataJaxbUnitTests.java
Normal file → Executable file
11
src/test/java/org/springframework/data/domain/jaxb/SpringDataJaxbUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.domain.jaxb;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
@@ -85,7 +84,7 @@ public class SpringDataJaxbUnitTests {
|
||||
wrapper.pageableWithoutSort = new PageRequest(10, 20);
|
||||
marshaller.marshal(wrapper, writer);
|
||||
|
||||
assertThat(new Diff(reference, writer.toString()).similar(), is(true));
|
||||
assertThat(new Diff(reference, writer.toString()).similar()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -93,9 +92,9 @@ public class SpringDataJaxbUnitTests {
|
||||
|
||||
Object result = unmarshaller.unmarshal(resource.getFile());
|
||||
|
||||
assertThat(result, is(instanceOf(Wrapper.class)));
|
||||
assertThat(((Wrapper) result).pageable, is(pageable));
|
||||
assertThat(((Wrapper) result).sort, is(sort));
|
||||
assertThat(result).isInstanceOf(Wrapper.class);
|
||||
assertThat(((Wrapper) result).pageable).isEqualTo(pageable);
|
||||
assertThat(((Wrapper) result).sort).isEqualTo(sort);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
17
src/test/java/org/springframework/data/geo/BoxUnitTests.java
Normal file → Executable file
17
src/test/java/org/springframework/data/geo/BoxUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.geo;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.util.SerializationUtils;
|
||||
@@ -36,28 +35,28 @@ public class BoxUnitTests {
|
||||
@Test // DATACMNS-437
|
||||
public void equalsWorksCorrectly() {
|
||||
|
||||
assertThat(first.equals(second), is(true));
|
||||
assertThat(second.equals(first), is(true));
|
||||
assertThat(first.equals(third), is(false));
|
||||
assertThat(first.equals(second)).isTrue();
|
||||
assertThat(second.equals(first)).isTrue();
|
||||
assertThat(first.equals(third)).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-437
|
||||
public void hashCodeWorksCorrectly() {
|
||||
|
||||
assertThat(first.hashCode(), is(second.hashCode()));
|
||||
assertThat(first.hashCode(), is(not(third.hashCode())));
|
||||
assertThat(first.hashCode()).isEqualTo(second.hashCode());
|
||||
assertThat(first.hashCode()).isNotEqualTo(third.hashCode());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-437
|
||||
public void testToString() {
|
||||
|
||||
assertThat(first.toString(), is("Box [Point [x=1.000000, y=1.000000], Point [x=2.000000, y=2.000000]]"));
|
||||
assertThat(first.toString()).isEqualTo("Box [Point [x=1.000000, y=1.000000], Point [x=2.000000, y=2.000000]]");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-482
|
||||
public void testSerialization() {
|
||||
|
||||
Box serialized = (Box) SerializationUtils.deserialize(SerializationUtils.serialize(first));
|
||||
assertThat(serialized, is(first));
|
||||
assertThat(serialized).isEqualTo(first);
|
||||
}
|
||||
}
|
||||
|
||||
15
src/test/java/org/springframework/data/geo/CircleUnitTests.java
Normal file → Executable file
15
src/test/java/org/springframework/data/geo/CircleUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.geo;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.util.SerializationUtils;
|
||||
@@ -45,19 +44,19 @@ public class CircleUnitTests {
|
||||
Circle left = new Circle(1, 1, 1);
|
||||
Circle right = new Circle(1, 1, 1);
|
||||
|
||||
assertThat(left, is(right));
|
||||
assertThat(right, is(left));
|
||||
assertThat(left).isEqualTo(right);
|
||||
assertThat(right).isEqualTo(left);
|
||||
|
||||
right = new Circle(new Point(1, 1), new Distance(1));
|
||||
|
||||
assertThat(left, is(right));
|
||||
assertThat(right, is(left));
|
||||
assertThat(left).isEqualTo(right);
|
||||
assertThat(right).isEqualTo(left);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-437
|
||||
public void testToString() {
|
||||
|
||||
assertThat(new Circle(1, 1, 1).toString(), is("Circle: [center=Point [x=1.000000, y=1.000000], radius=1.0]"));
|
||||
assertThat(new Circle(1, 1, 1).toString()).isEqualTo("Circle: [center=Point [x=1.000000, y=1.000000], radius=1.0]");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-482
|
||||
@@ -66,6 +65,6 @@ public class CircleUnitTests {
|
||||
Circle circle = new Circle(1, 1, 1);
|
||||
|
||||
Circle serialized = (Circle) SerializationUtils.deserialize(SerializationUtils.serialize(circle));
|
||||
assertThat(serialized, is(circle));
|
||||
assertThat(serialized).isEqualTo(circle);
|
||||
}
|
||||
}
|
||||
|
||||
81
src/test/java/org/springframework/data/geo/DistanceUnitTests.java
Normal file → Executable file
81
src/test/java/org/springframework/data/geo/DistanceUnitTests.java
Normal file → Executable file
@@ -15,10 +15,10 @@
|
||||
*/
|
||||
package org.springframework.data.geo;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.geo.Metrics.*;
|
||||
|
||||
import org.assertj.core.data.Offset;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Range;
|
||||
import org.springframework.util.SerializationUtils;
|
||||
@@ -31,15 +31,15 @@ import org.springframework.util.SerializationUtils;
|
||||
*/
|
||||
public class DistanceUnitTests {
|
||||
|
||||
private static final double EPS = 0.000000001;
|
||||
private static final Offset<Double> EPS = Offset.offset(0.000000001);
|
||||
private static final double TEN_MILES_NORMALIZED = 0.002523219294755161;
|
||||
private static final double TEN_KM_NORMALIZED = 0.001567855942887398;
|
||||
|
||||
@Test // DATACMNS-437
|
||||
public void defaultsMetricToNeutralOne() {
|
||||
|
||||
assertThat(new Distance(2.5).getMetric(), is((Metric) Metrics.NEUTRAL));
|
||||
assertThat(new Distance(2.5, null).getMetric(), is((Metric) Metrics.NEUTRAL));
|
||||
assertThat(new Distance(2.5).getMetric()).isEqualTo((Metric) Metrics.NEUTRAL);
|
||||
assertThat(new Distance(2.5, null).getMetric()).isEqualTo((Metric) Metrics.NEUTRAL);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-437
|
||||
@@ -48,7 +48,7 @@ public class DistanceUnitTests {
|
||||
Distance left = new Distance(2.5, KILOMETERS);
|
||||
Distance right = new Distance(2.5, KILOMETERS);
|
||||
|
||||
assertThat(left.add(right), is(new Distance(5.0, KILOMETERS)));
|
||||
assertThat(left.add(right)).isEqualTo(new Distance(5.0, KILOMETERS));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-437
|
||||
@@ -57,52 +57,53 @@ public class DistanceUnitTests {
|
||||
Distance left = new Distance(2.5, KILOMETERS);
|
||||
Distance right = new Distance(2.5, KILOMETERS);
|
||||
|
||||
assertThat(left.add(right, MILES), is(new Distance(3.106856281073925, MILES)));
|
||||
assertThat(left.add(right, MILES)).isEqualTo(new Distance(3.106856281073925, MILES));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-474
|
||||
public void distanceWithSameMetricShoudEqualAfterConversion() {
|
||||
|
||||
assertThat(new Distance(1).in(NEUTRAL), is(new Distance(1)));
|
||||
assertThat(new Distance(TEN_KM_NORMALIZED).in(KILOMETERS), is(new Distance(10, KILOMETERS)));
|
||||
assertThat(new Distance(TEN_MILES_NORMALIZED).in(MILES), is(new Distance(10, MILES)));
|
||||
assertThat(new Distance(1).in(NEUTRAL)).isEqualTo(new Distance(1));
|
||||
assertThat(new Distance(TEN_KM_NORMALIZED).in(KILOMETERS)).isEqualTo(new Distance(10, KILOMETERS));
|
||||
assertThat(new Distance(TEN_MILES_NORMALIZED).in(MILES)).isEqualTo(new Distance(10, MILES));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-474
|
||||
public void distanceWithDifferentMetricShoudEqualAfterConversion() {
|
||||
|
||||
assertThat(new Distance(10, MILES), is(new Distance(TEN_MILES_NORMALIZED).in(MILES)));
|
||||
assertThat(new Distance(10, KILOMETERS), is(new Distance(TEN_KM_NORMALIZED).in(KILOMETERS)));
|
||||
assertThat(new Distance(10, MILES)).isEqualTo(new Distance(TEN_MILES_NORMALIZED).in(MILES));
|
||||
assertThat(new Distance(10, KILOMETERS)).isEqualTo(new Distance(TEN_KM_NORMALIZED).in(KILOMETERS));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-474
|
||||
public void conversionShouldProduceCorrectNormalizedValue() {
|
||||
|
||||
assertThat(new Distance(TEN_KM_NORMALIZED, NEUTRAL).in(KILOMETERS).getNormalizedValue(),
|
||||
closeTo(new Distance(10, KILOMETERS).getNormalizedValue(), EPS));
|
||||
assertThat(new Distance(TEN_KM_NORMALIZED, NEUTRAL).in(KILOMETERS).getNormalizedValue())
|
||||
.isCloseTo(new Distance(10, KILOMETERS).getNormalizedValue(), EPS);
|
||||
|
||||
assertThat(new Distance(TEN_KM_NORMALIZED).in(KILOMETERS).getNormalizedValue(),
|
||||
closeTo(new Distance(10, KILOMETERS).getNormalizedValue(), EPS));
|
||||
assertThat(new Distance(TEN_KM_NORMALIZED).in(KILOMETERS).getNormalizedValue())
|
||||
.isCloseTo(new Distance(10, KILOMETERS).getNormalizedValue(), EPS);
|
||||
|
||||
assertThat(new Distance(TEN_MILES_NORMALIZED).in(MILES).getNormalizedValue(),
|
||||
closeTo(new Distance(10, MILES).getNormalizedValue(), EPS));
|
||||
assertThat(new Distance(TEN_MILES_NORMALIZED).in(MILES).getNormalizedValue())
|
||||
.isCloseTo(new Distance(10, MILES).getNormalizedValue(), EPS);
|
||||
|
||||
assertThat(new Distance(TEN_MILES_NORMALIZED).in(MILES).getNormalizedValue(),
|
||||
closeTo(new Distance(16.09344, KILOMETERS).getNormalizedValue(), EPS));
|
||||
assertThat(new Distance(TEN_MILES_NORMALIZED).in(MILES).getNormalizedValue())
|
||||
.isCloseTo(new Distance(16.09344, KILOMETERS).getNormalizedValue(), EPS);
|
||||
|
||||
assertThat(new Distance(TEN_MILES_NORMALIZED).in(KILOMETERS).getNormalizedValue(),
|
||||
closeTo(new Distance(10, MILES).getNormalizedValue(), EPS));
|
||||
assertThat(new Distance(TEN_MILES_NORMALIZED).in(KILOMETERS).getNormalizedValue())
|
||||
.isCloseTo(new Distance(10, MILES).getNormalizedValue(), EPS);
|
||||
|
||||
assertThat(new Distance(10, KILOMETERS).in(MILES).getNormalizedValue(),
|
||||
closeTo(new Distance(6.21371192, MILES).getNormalizedValue(), EPS));
|
||||
assertThat(new Distance(10, KILOMETERS).in(MILES).getNormalizedValue())
|
||||
.isCloseTo(new Distance(6.21371192, MILES).getNormalizedValue(), EPS);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-474
|
||||
public void toStringAfterConversion() {
|
||||
|
||||
assertThat(new Distance(10, KILOMETERS).in(MILES).toString(), is(new Distance(6.21371256214785, MILES).toString()));
|
||||
assertThat(new Distance(6.21371256214785, MILES).in(KILOMETERS).toString(),
|
||||
is(new Distance(10, KILOMETERS).toString()));
|
||||
assertThat(new Distance(10, KILOMETERS).in(MILES).toString())
|
||||
.isEqualTo(new Distance(6.21371256214785, MILES).toString());
|
||||
assertThat(new Distance(6.21371256214785, MILES).in(KILOMETERS).toString())
|
||||
.isEqualTo(new Distance(10, KILOMETERS).toString());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-482
|
||||
@@ -111,12 +112,12 @@ public class DistanceUnitTests {
|
||||
Distance dist = new Distance(10, KILOMETERS);
|
||||
|
||||
Distance serialized = (Distance) SerializationUtils.deserialize(SerializationUtils.serialize(dist));
|
||||
assertThat(serialized, is(dist));
|
||||
assertThat(serialized).isEqualTo(dist);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-626
|
||||
public void returnsMetricsAbbreviationAsUnit() {
|
||||
assertThat(new Distance(10, KILOMETERS).getUnit(), is("km"));
|
||||
assertThat(new Distance(10, KILOMETERS).getUnit()).isEqualTo("km");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-651
|
||||
@@ -127,9 +128,9 @@ public class DistanceUnitTests {
|
||||
|
||||
Range<Distance> range = Distance.between(twoKilometers, tenKilometers);
|
||||
|
||||
assertThat(range, is(notNullValue()));
|
||||
assertThat(range.getLowerBound(), is(twoKilometers));
|
||||
assertThat(range.getUpperBound(), is(tenKilometers));
|
||||
assertThat(range).isNotNull();
|
||||
assertThat(range.getLowerBound()).isEqualTo(twoKilometers);
|
||||
assertThat(range.getUpperBound()).isEqualTo(tenKilometers);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-651
|
||||
@@ -140,9 +141,9 @@ public class DistanceUnitTests {
|
||||
|
||||
Range<Distance> range = Distance.between(2, KILOMETERS, 10, KILOMETERS);
|
||||
|
||||
assertThat(range, is(notNullValue()));
|
||||
assertThat(range.getLowerBound(), is(twoKilometers));
|
||||
assertThat(range.getUpperBound(), is(tenKilometers));
|
||||
assertThat(range).isNotNull();
|
||||
assertThat(range.getLowerBound()).isEqualTo(twoKilometers);
|
||||
assertThat(range.getUpperBound()).isEqualTo(tenKilometers);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-651
|
||||
@@ -152,11 +153,11 @@ public class DistanceUnitTests {
|
||||
Distance tenKilometers = new Distance(10, KILOMETERS);
|
||||
Distance tenKilometersInMiles = new Distance(6.21371256214785, MILES);
|
||||
|
||||
assertThat(tenKilometers.compareTo(tenKilometers), is(0));
|
||||
assertThat(tenKilometers.compareTo(tenKilometersInMiles), is(0));
|
||||
assertThat(tenKilometersInMiles.compareTo(tenKilometers), is(0));
|
||||
assertThat(tenKilometers.compareTo(tenKilometers)).isEqualTo(0);
|
||||
assertThat(tenKilometers.compareTo(tenKilometersInMiles)).isEqualTo(0);
|
||||
assertThat(tenKilometersInMiles.compareTo(tenKilometers)).isEqualTo(0);
|
||||
|
||||
assertThat(twoKilometers.compareTo(tenKilometers), is(lessThan(0)));
|
||||
assertThat(tenKilometers.compareTo(twoKilometers), is(greaterThan(0)));
|
||||
assertThat(twoKilometers.compareTo(tenKilometers)).isLessThan(0);
|
||||
assertThat(tenKilometers.compareTo(twoKilometers)).isGreaterThan(0);
|
||||
}
|
||||
}
|
||||
|
||||
23
src/test/java/org/springframework/data/geo/GeoModuleIntegrationTests.java
Normal file → Executable file
23
src/test/java/org/springframework/data/geo/GeoModuleIntegrationTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.geo;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
@@ -45,8 +44,8 @@ public class GeoModuleIntegrationTests {
|
||||
String json = "{\"value\":10.0,\"metric\":\"KILOMETERS\"}";
|
||||
Distance reference = new Distance(10.0, Metrics.KILOMETERS);
|
||||
|
||||
assertThat(mapper.readValue(json, Distance.class), is(reference));
|
||||
assertThat(mapper.writeValueAsString(reference), is(json));
|
||||
assertThat(mapper.readValue(json, Distance.class)).isEqualTo(reference);
|
||||
assertThat(mapper.writeValueAsString(reference)).isEqualTo(json);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-475
|
||||
@@ -55,8 +54,8 @@ public class GeoModuleIntegrationTests {
|
||||
String json = "{\"x\":10.0,\"y\":20.0}";
|
||||
Point reference = new Point(10.0, 20.0);
|
||||
|
||||
assertThat(mapper.readValue(json, Point.class), is(reference));
|
||||
assertThat(mapper.writeValueAsString(reference), is(json));
|
||||
assertThat(mapper.readValue(json, Point.class)).isEqualTo(reference);
|
||||
assertThat(mapper.writeValueAsString(reference)).isEqualTo(json);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-475
|
||||
@@ -65,8 +64,8 @@ public class GeoModuleIntegrationTests {
|
||||
String json = "{\"center\":{\"x\":10.0,\"y\":20.0},\"radius\":{\"value\":10.0,\"metric\":\"KILOMETERS\"}}";
|
||||
Circle reference = new Circle(new Point(10.0, 20.0), new Distance(10, Metrics.KILOMETERS));
|
||||
|
||||
assertThat(mapper.readValue(json, Circle.class), is(reference));
|
||||
assertThat(mapper.writeValueAsString(reference), is(json));
|
||||
assertThat(mapper.readValue(json, Circle.class)).isEqualTo(reference);
|
||||
assertThat(mapper.writeValueAsString(reference)).isEqualTo(json);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-475
|
||||
@@ -75,8 +74,8 @@ public class GeoModuleIntegrationTests {
|
||||
String json = "{\"first\":{\"x\":1.0,\"y\":2.0},\"second\":{\"x\":2.0,\"y\":3.0}}";
|
||||
Box reference = new Box(new Point(1, 2), new Point(2, 3));
|
||||
|
||||
assertThat(mapper.readValue(json, Box.class), is(reference));
|
||||
assertThat(mapper.writeValueAsString(reference), is(json));
|
||||
assertThat(mapper.readValue(json, Box.class)).isEqualTo(reference);
|
||||
assertThat(mapper.writeValueAsString(reference)).isEqualTo(json);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-475
|
||||
@@ -85,7 +84,7 @@ public class GeoModuleIntegrationTests {
|
||||
String json = "{\"points\":[{\"x\":1.0,\"y\":2.0},{\"x\":2.0,\"y\":3.0},{\"x\":3.0,\"y\":4.0}]}";
|
||||
Polygon reference = new Polygon(new Point(1, 2), new Point(2, 3), new Point(3, 4));
|
||||
|
||||
assertThat(mapper.readValue(json, Polygon.class), is(reference));
|
||||
assertThat(mapper.writeValueAsString(reference), is(json));
|
||||
assertThat(mapper.readValue(json, Polygon.class)).isEqualTo(reference);
|
||||
assertThat(mapper.writeValueAsString(reference)).isEqualTo(json);
|
||||
}
|
||||
}
|
||||
|
||||
19
src/test/java/org/springframework/data/geo/GeoResultUnitTests.java
Normal file → Executable file
19
src/test/java/org/springframework/data/geo/GeoResultUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.geo;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.util.SerializationUtils;
|
||||
@@ -37,18 +36,18 @@ public class GeoResultUnitTests {
|
||||
@Test // DATACMNS-437
|
||||
public void considersSameInstanceEqual() {
|
||||
|
||||
assertThat(first.equals(first), is(true));
|
||||
assertThat(first.equals(first)).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-437
|
||||
public void considersSameValuesAsEqual() {
|
||||
|
||||
assertThat(first.equals(second), is(true));
|
||||
assertThat(second.equals(first), is(true));
|
||||
assertThat(first.equals(third), is(false));
|
||||
assertThat(third.equals(first), is(false));
|
||||
assertThat(first.equals(fourth), is(false));
|
||||
assertThat(fourth.equals(first), is(false));
|
||||
assertThat(first.equals(second)).isTrue();
|
||||
assertThat(second.equals(first)).isTrue();
|
||||
assertThat(first.equals(third)).isFalse();
|
||||
assertThat(third.equals(first)).isFalse();
|
||||
assertThat(first.equals(fourth)).isFalse();
|
||||
assertThat(fourth.equals(first)).isFalse();
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
@@ -64,6 +63,6 @@ public class GeoResultUnitTests {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
GeoResult<String> serialized = (GeoResult<String>) SerializationUtils.deserialize(SerializationUtils.serialize(result));
|
||||
assertThat(serialized, is(result));
|
||||
assertThat(serialized).isEqualTo(result);
|
||||
}
|
||||
}
|
||||
|
||||
22
src/test/java/org/springframework/data/geo/GeoResultsUnitTests.java
Normal file → Executable file
22
src/test/java/org/springframework/data/geo/GeoResultsUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.geo;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
@@ -35,23 +34,22 @@ public class GeoResultsUnitTests {
|
||||
@SuppressWarnings("unchecked")
|
||||
public void calculatesAverageForGivenGeoResults() {
|
||||
|
||||
GeoResult<Object> first = new GeoResult<Object>(new Object(), new Distance(2));
|
||||
GeoResult<Object> second = new GeoResult<Object>(new Object(), new Distance(5));
|
||||
GeoResults<Object> geoResults = new GeoResults<Object>(Arrays.asList(first, second));
|
||||
GeoResult<Object> first = new GeoResult<>(new Object(), new Distance(2));
|
||||
GeoResult<Object> second = new GeoResult<>(new Object(), new Distance(5));
|
||||
GeoResults<Object> geoResults = new GeoResults<>(Arrays.asList(first, second));
|
||||
|
||||
assertThat(geoResults.getAverageDistance(), is(new Distance(3.5)));
|
||||
assertThat(geoResults.getAverageDistance()).isEqualTo(new Distance(3.5));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-482
|
||||
public void testSerialization() {
|
||||
|
||||
GeoResult<String> result = new GeoResult<String>("test", new Distance(2));
|
||||
@SuppressWarnings("unchecked")
|
||||
GeoResults<String> geoResults = new GeoResults<String>(Arrays.asList(result));
|
||||
GeoResult<String> result = new GeoResult<>("test", new Distance(2));
|
||||
GeoResults<String> geoResults = new GeoResults<>(Arrays.asList(result));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
GeoResults<String> serialized = (GeoResults<String>) SerializationUtils.deserialize(SerializationUtils
|
||||
.serialize(geoResults));
|
||||
assertThat(serialized, is(geoResults));
|
||||
GeoResults<String> serialized = (GeoResults<String>) SerializationUtils
|
||||
.deserialize(SerializationUtils.serialize(geoResults));
|
||||
assertThat(serialized).isEqualTo(geoResults);
|
||||
}
|
||||
}
|
||||
|
||||
13
src/test/java/org/springframework/data/geo/PointUnitTests.java
Normal file → Executable file
13
src/test/java/org/springframework/data/geo/PointUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.geo;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.util.SerializationUtils;
|
||||
@@ -37,14 +36,14 @@ public class PointUnitTests {
|
||||
@Test // DATACMNS-437
|
||||
public void equalsIsImplementedCorrectly() {
|
||||
|
||||
assertThat(new Point(1.5, 1.5), is(equalTo(new Point(1.5, 1.5))));
|
||||
assertThat(new Point(1.5, 1.5), is(not(equalTo(new Point(2.0, 2.0)))));
|
||||
assertThat(new Point(2.0, 2.0), is(not(equalTo(new Point(1.5, 1.5)))));
|
||||
assertThat(new Point(1.5, 1.5)).isEqualTo(new Point(1.5, 1.5));
|
||||
assertThat(new Point(1.5, 1.5)).isNotEqualTo(new Point(2.0, 2.0));
|
||||
assertThat(new Point(2.0, 2.0)).isNotEqualTo(new Point(1.5, 1.5));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-437
|
||||
public void invokingToStringWorksCorrectly() {
|
||||
assertThat(new Point(1.5, 1.5).toString(), is("Point [x=1.500000, y=1.500000]"));
|
||||
assertThat(new Point(1.5, 1.5).toString()).isEqualTo("Point [x=1.500000, y=1.500000]");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-482
|
||||
@@ -53,6 +52,6 @@ public class PointUnitTests {
|
||||
Point point = new Point(1.5, 1.5);
|
||||
|
||||
Point serialized = (Point) SerializationUtils.deserialize(SerializationUtils.serialize(point));
|
||||
assertThat(serialized, is(point));
|
||||
assertThat(serialized).isEqualTo(point);
|
||||
}
|
||||
}
|
||||
|
||||
15
src/test/java/org/springframework/data/geo/PolygonUnitTests.java
Normal file → Executable file
15
src/test/java/org/springframework/data/geo/PolygonUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.geo;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.util.SerializationUtils;
|
||||
@@ -43,7 +42,7 @@ public class PolygonUnitTests {
|
||||
|
||||
Polygon polygon = new Polygon(third, second, first);
|
||||
|
||||
assertThat(polygon, is(notNullValue()));
|
||||
assertThat(polygon).isNotNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-437
|
||||
@@ -52,15 +51,15 @@ public class PolygonUnitTests {
|
||||
Polygon left = new Polygon(third, second, first);
|
||||
Polygon right = new Polygon(third, second, first);
|
||||
|
||||
assertThat(left, is(right));
|
||||
assertThat(right, is(left));
|
||||
assertThat(left).isEqualTo(right);
|
||||
assertThat(right).isEqualTo(left);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-437
|
||||
public void testToString() {
|
||||
|
||||
assertThat(new Polygon(third, second, first).toString(),
|
||||
is("Polygon: [Point [x=3.000000, y=3.000000],Point [x=2.000000, y=2.000000],Point [x=1.000000, y=1.000000]]"));
|
||||
assertThat(new Polygon(third, second, first).toString()).isEqualTo(
|
||||
"Polygon: [Point [x=3.000000, y=3.000000],Point [x=2.000000, y=2.000000],Point [x=1.000000, y=1.000000]]");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-482
|
||||
@@ -69,6 +68,6 @@ public class PolygonUnitTests {
|
||||
Polygon polygon = new Polygon(third, second, first);
|
||||
|
||||
Polygon serialized = (Polygon) SerializationUtils.deserialize(SerializationUtils.serialize(polygon));
|
||||
assertThat(serialized, is(polygon));
|
||||
assertThat(serialized).isEqualTo(polygon);
|
||||
}
|
||||
}
|
||||
|
||||
9
src/test/java/org/springframework/data/geo/format/DistanceFormatterUnitTests.java
Normal file → Executable file
9
src/test/java/org/springframework/data/geo/format/DistanceFormatterUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.geo.format;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.geo.format.DistanceFormatter.*;
|
||||
|
||||
import java.text.ParseException;
|
||||
@@ -62,7 +61,7 @@ public class DistanceFormatterUnitTests {
|
||||
|
||||
@Test // DATAREST-279, DATACMNS-626
|
||||
public void printsDistance() {
|
||||
assertThat(INSTANCE.print(REFERENCE, Locale.US), is("10.8km"));
|
||||
assertThat(INSTANCE.print(REFERENCE, Locale.US)).isEqualTo("10.8km");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,12 +79,12 @@ public class DistanceFormatterUnitTests {
|
||||
|
||||
@Test // DATAREST-279, DATACMNS-626
|
||||
public void parsesDistanceFromString() {
|
||||
assertThat(INSTANCE.convert(source), is(REFERENCE));
|
||||
assertThat(INSTANCE.convert(source)).isEqualTo(REFERENCE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parsesDistances() throws ParseException {
|
||||
assertThat(INSTANCE.parse(source, Locale.US), is(REFERENCE));
|
||||
assertThat(INSTANCE.parse(source, Locale.US)).isEqualTo(REFERENCE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
7
src/test/java/org/springframework/data/geo/format/PointFormatterUnitTests.java
Normal file → Executable file
7
src/test/java/org/springframework/data/geo/format/PointFormatterUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.geo.format;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.geo.format.PointFormatter.*;
|
||||
|
||||
import java.text.ParseException;
|
||||
@@ -86,12 +85,12 @@ public class PointFormatterUnitTests {
|
||||
|
||||
@Test // DATAREST-279, DATACMNS-626
|
||||
public void convertsPointFromString() {
|
||||
assertThat(INSTANCE.convert(source), is(REFERENCE));
|
||||
assertThat(INSTANCE.convert(source)).isEqualTo(REFERENCE);
|
||||
}
|
||||
|
||||
@Test // DATAREST-279, DATACMNS-626
|
||||
public void parsesPoint() throws ParseException {
|
||||
assertThat(INSTANCE.parse(source, Locale.US), is(REFERENCE));
|
||||
assertThat(INSTANCE.parse(source, Locale.US)).isEqualTo(REFERENCE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,15 +15,15 @@
|
||||
*/
|
||||
package org.springframework.data.history;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
@@ -37,51 +37,43 @@ import org.mockito.runners.MockitoJUnitRunner;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class RevisionUnitTests {
|
||||
|
||||
@Mock
|
||||
RevisionMetadata<Integer> firstMetadata, secondMetadata;
|
||||
@Mock RevisionMetadata<Integer> firstMetadata, secondMetadata;
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void comparesCorrectly() {
|
||||
|
||||
when(firstMetadata.getRevisionNumber()).thenReturn(1);
|
||||
when(secondMetadata.getRevisionNumber()).thenReturn(2);
|
||||
when(firstMetadata.getRevisionNumber()).thenReturn(Optional.of(1));
|
||||
when(secondMetadata.getRevisionNumber()).thenReturn(Optional.of(2));
|
||||
|
||||
Revision<Integer, Object> first = new Revision<Integer, Object>(firstMetadata, new Object());
|
||||
Revision<Integer, Object> second = new Revision<Integer, Object>(secondMetadata, new Object());
|
||||
Revision<Integer, Object> first = Revision.of(firstMetadata, new Object());
|
||||
Revision<Integer, Object> second = Revision.of(secondMetadata, new Object());
|
||||
|
||||
List<Revision<Integer, Object>> revisions = Arrays.asList(second, first);
|
||||
Collections.sort(revisions);
|
||||
List<Revision<Integer, Object>> revisions = Stream.of(second, first).sorted().collect(Collectors.toList());
|
||||
|
||||
assertThat(revisions.get(0), is(first));
|
||||
assertThat(revisions.get(1), is(second));
|
||||
assertThat(revisions.get(0)).isEqualTo(first);
|
||||
assertThat(revisions.get(1)).isEqualTo(second);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-187
|
||||
public void returnsRevisionNumber() {
|
||||
|
||||
when(firstMetadata.getRevisionNumber()).thenReturn(4711);
|
||||
Optional<Integer> reference = Optional.of(4711);
|
||||
when(firstMetadata.getRevisionNumber()).thenReturn(reference);
|
||||
|
||||
Revision<Integer, Object> revision = new Revision<Integer, Object>(firstMetadata, new Object());
|
||||
|
||||
assertThat(revision.getRevisionNumber(), is(4711));
|
||||
assertThat(Revision.of(firstMetadata, new Object()).getRevisionNumber()).isEqualTo(reference);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-187
|
||||
public void returnsRevisionDate() {
|
||||
|
||||
DateTime reference = new DateTime();
|
||||
Optional<LocalDateTime> reference = Optional.of(LocalDateTime.now());
|
||||
when(firstMetadata.getRevisionDate()).thenReturn(reference);
|
||||
|
||||
Revision<Integer, Object> revision = new Revision<Integer, Object>(firstMetadata, new Object());
|
||||
|
||||
assertThat(revision.getRevisionDate(), is(reference));
|
||||
assertThat(Revision.of(firstMetadata, new Object()).getRevisionDate()).isEqualTo(reference);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-218
|
||||
public void returnsRevisionMetadata() {
|
||||
|
||||
Revision<Integer, Object> revision = new Revision<Integer, Object>(firstMetadata, new Object());
|
||||
assertThat(revision.getMetadata(), is(firstMetadata));
|
||||
assertThat(Revision.of(firstMetadata, new Object()).getMetadata()).isEqualTo(firstMetadata);
|
||||
}
|
||||
}
|
||||
|
||||
66
src/test/java/org/springframework/data/history/RevisionsUnitTests.java
Normal file → Executable file
66
src/test/java/org/springframework/data/history/RevisionsUnitTests.java
Normal file → Executable file
@@ -15,12 +15,12 @@
|
||||
*/
|
||||
package org.springframework.data.history;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
@@ -36,75 +36,67 @@ import org.mockito.runners.MockitoJUnitRunner;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class RevisionsUnitTests {
|
||||
|
||||
@Mock
|
||||
RevisionMetadata<Integer> first, second;
|
||||
@Mock RevisionMetadata<Integer> first, second;
|
||||
Revision<Integer, Object> firstRevision, secondRevision;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
|
||||
when(first.getRevisionNumber()).thenReturn(0);
|
||||
when(second.getRevisionNumber()).thenReturn(10);
|
||||
when(first.getRevisionNumber()).thenReturn(Optional.of(0));
|
||||
when(second.getRevisionNumber()).thenReturn(Optional.of(10));
|
||||
|
||||
firstRevision = new Revision<Integer, Object>(first, new Object());
|
||||
secondRevision = new Revision<Integer, Object>(second, new Object());
|
||||
firstRevision = Revision.of(first, new Object());
|
||||
secondRevision = Revision.of(second, new Object());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void returnsCorrectLatestRevision() {
|
||||
|
||||
Revisions<Integer, Object> revisions = new Revisions<Integer, Object>(Arrays.asList(firstRevision, secondRevision));
|
||||
assertThat(revisions.getLatestRevision(), is(secondRevision));
|
||||
assertThat(Revisions.of(Arrays.asList(firstRevision, secondRevision)).getLatestRevision())
|
||||
.isEqualTo(secondRevision);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void iteratesInCorrectOrder() {
|
||||
|
||||
Revisions<Integer, Object> revisions = new Revisions<Integer, Object>(Arrays.asList(firstRevision, secondRevision));
|
||||
Revisions<Integer, Object> revisions = Revisions.of(Arrays.asList(firstRevision, secondRevision));
|
||||
Iterator<Revision<Integer, Object>> iterator = revisions.iterator();
|
||||
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(firstRevision));
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(secondRevision));
|
||||
assertThat(iterator.hasNext(), is(false));
|
||||
assertThat(iterator.hasNext()).isTrue();
|
||||
assertThat(iterator.next()).isEqualTo(firstRevision);
|
||||
assertThat(iterator.hasNext()).isTrue();
|
||||
assertThat(iterator.next()).isEqualTo(secondRevision);
|
||||
assertThat(iterator.hasNext()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void reversedRevisionsStillReturnsCorrectLatestRevision() {
|
||||
|
||||
Revisions<Integer, Object> revisions = new Revisions<Integer, Object>(Arrays.asList(firstRevision, secondRevision));
|
||||
assertThat(revisions.reverse().getLatestRevision(), is(secondRevision));
|
||||
assertThat(Revisions.of(Arrays.asList(firstRevision, secondRevision)).reverse().getLatestRevision())
|
||||
.isEqualTo(secondRevision);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void iteratesReversedRevisionsInCorrectOrder() {
|
||||
|
||||
Revisions<Integer, Object> revisions = new Revisions<Integer, Object>(Arrays.asList(firstRevision, secondRevision));
|
||||
Revisions<Integer, Object> revisions = Revisions.of(Arrays.asList(firstRevision, secondRevision));
|
||||
Iterator<Revision<Integer, Object>> iterator = revisions.reverse().iterator();
|
||||
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(secondRevision));
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(firstRevision));
|
||||
assertThat(iterator.hasNext(), is(false));
|
||||
assertThat(iterator.hasNext()).isTrue();
|
||||
assertThat(iterator.next()).isEqualTo(secondRevision);
|
||||
assertThat(iterator.hasNext()).isTrue();
|
||||
assertThat(iterator.next()).isEqualTo(firstRevision);
|
||||
assertThat(iterator.hasNext()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void forcesInvalidlyOrderedRevisionsToBeOrdered() {
|
||||
|
||||
Revisions<Integer, Object> revisions = new Revisions<Integer, Object>(Arrays.asList(secondRevision, firstRevision));
|
||||
Revisions<Integer, Object> revisions = Revisions.of(Arrays.asList(secondRevision, firstRevision));
|
||||
Iterator<Revision<Integer, Object>> iterator = revisions.iterator();
|
||||
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(firstRevision));
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(secondRevision));
|
||||
assertThat(iterator.hasNext(), is(false));
|
||||
assertThat(iterator.hasNext()).isTrue();
|
||||
assertThat(iterator.next()).isEqualTo(firstRevision);
|
||||
assertThat(iterator.hasNext()).isTrue();
|
||||
assertThat(iterator.next()).isEqualTo(secondRevision);
|
||||
assertThat(iterator.hasNext()).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
22
src/test/java/org/springframework/data/mapping/MappingMetadataTests.java
Normal file → Executable file
22
src/test/java/org/springframework/data/mapping/MappingMetadataTests.java
Normal file → Executable file
@@ -15,9 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.Collections;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
@@ -42,25 +40,17 @@ public class MappingMetadataTests {
|
||||
@Test
|
||||
public void testPojoWithId() {
|
||||
|
||||
ctx.setInitialEntitySet(Collections.singleton(PersonWithId.class));
|
||||
ctx.initialize();
|
||||
|
||||
PersistentEntity<?, SamplePersistentProperty> person = ctx.getPersistentEntity(PersonWithId.class);
|
||||
assertNotNull(person.getIdProperty());
|
||||
assertEquals(String.class, person.getIdProperty().getType());
|
||||
|
||||
assertThat(person.getIdProperty()).hasValueSatisfying(it -> assertThat(it.getType()).isEqualTo(String.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAssociations() {
|
||||
|
||||
ctx.setInitialEntitySet(Collections.singleton(PersonWithChildren.class));
|
||||
ctx.initialize();
|
||||
|
||||
PersistentEntity<?, SamplePersistentProperty> person = ctx.getPersistentEntity(PersonWithChildren.class);
|
||||
person.doWithAssociations(new AssociationHandler<SamplePersistentProperty>() {
|
||||
public void doWithAssociation(Association<SamplePersistentProperty> association) {
|
||||
assertEquals(Child.class, association.getInverse().getComponentType());
|
||||
}
|
||||
});
|
||||
|
||||
person.doWithAssociations((AssociationHandler<SamplePersistentProperty>) association -> assertThat(
|
||||
association.getInverse().getComponentType()).isEqualTo(Child.class));
|
||||
}
|
||||
}
|
||||
|
||||
50
src/test/java/org/springframework/data/mapping/ParameterUnitTests.java
Normal file → Executable file
50
src/test/java/org/springframework/data/mapping/ParameterUnitTests.java
Normal file → Executable file
@@ -15,10 +15,10 @@
|
||||
*/
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
@@ -36,10 +36,8 @@ import org.springframework.data.util.TypeInformation;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ParameterUnitTests<P extends PersistentProperty<P>> {
|
||||
|
||||
@Mock
|
||||
PersistentEntity<Object, P> entity;
|
||||
@Mock
|
||||
PersistentEntity<String, P> stringEntity;
|
||||
@Mock PersistentEntity<Object, P> entity;
|
||||
@Mock PersistentEntity<String, P> stringEntity;
|
||||
|
||||
TypeInformation<Object> type = ClassTypeInformation.from(Object.class);
|
||||
Annotation[] annotations = new Annotation[0];
|
||||
@@ -47,50 +45,50 @@ public class ParameterUnitTests<P extends PersistentProperty<P>> {
|
||||
@Test
|
||||
public void twoParametersWithIdenticalSetupEqual() {
|
||||
|
||||
Parameter<Object, P> left = new Parameter<Object, P>("name", type, annotations, entity);
|
||||
Parameter<Object, P> right = new Parameter<Object, P>("name", type, annotations, entity);
|
||||
Parameter<Object, P> left = new Parameter<Object, P>(Optional.of("name"), type, annotations, Optional.of(entity));
|
||||
Parameter<Object, P> right = new Parameter<Object, P>(Optional.of("name"), type, annotations, Optional.of(entity));
|
||||
|
||||
assertThat(left, is(right));
|
||||
assertThat(left.hashCode(), is(right.hashCode()));
|
||||
assertThat(left).isEqualTo(right);
|
||||
assertThat(left.hashCode()).isEqualTo(right.hashCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void twoParametersWithIdenticalSetupAndNullNameEqual() {
|
||||
|
||||
Parameter<Object, P> left = new Parameter<Object, P>(null, type, annotations, entity);
|
||||
Parameter<Object, P> right = new Parameter<Object, P>(null, type, annotations, entity);
|
||||
Parameter<Object, P> left = new Parameter<Object, P>(Optional.empty(), type, annotations, Optional.of(entity));
|
||||
Parameter<Object, P> right = new Parameter<Object, P>(Optional.empty(), type, annotations, Optional.of(entity));
|
||||
|
||||
assertThat(left, is(right));
|
||||
assertThat(left.hashCode(), is(right.hashCode()));
|
||||
assertThat(left).isEqualTo(right);
|
||||
assertThat(left.hashCode()).isEqualTo(right.hashCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void twoParametersWithIdenticalAndNullEntitySetupEqual() {
|
||||
|
||||
Parameter<Object, P> left = new Parameter<Object, P>("name", type, annotations, null);
|
||||
Parameter<Object, P> right = new Parameter<Object, P>("name", type, annotations, null);
|
||||
Parameter<Object, P> left = new Parameter<Object, P>(Optional.of("name"), type, annotations, Optional.empty());
|
||||
Parameter<Object, P> right = new Parameter<Object, P>(Optional.of("name"), type, annotations, Optional.empty());
|
||||
|
||||
assertThat(left, is(right));
|
||||
assertThat(left.hashCode(), is(right.hashCode()));
|
||||
assertThat(left).isEqualTo(right);
|
||||
assertThat(left.hashCode()).isEqualTo(right.hashCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void twoParametersWithDifferentNameAreNotEqual() {
|
||||
|
||||
Parameter<Object, P> left = new Parameter<Object, P>("first", type, annotations, entity);
|
||||
Parameter<Object, P> right = new Parameter<Object, P>("second", type, annotations, entity);
|
||||
Parameter<Object, P> left = new Parameter<Object, P>(Optional.of("first"), type, annotations, Optional.of(entity));
|
||||
Parameter<Object, P> right = new Parameter<Object, P>(Optional.of("second"), type, annotations,
|
||||
Optional.of(entity));
|
||||
|
||||
assertThat(left, is(not(right)));
|
||||
assertThat(left).isNotEqualTo(right);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("rawtypes")
|
||||
public void twoParametersWithDifferenTypeAreNotEqual() {
|
||||
|
||||
Parameter left = new Parameter<Object, P>("name", type, annotations, entity);
|
||||
Parameter right = new Parameter<String, P>("name", ClassTypeInformation.from(String.class), annotations,
|
||||
stringEntity);
|
||||
Parameter<Object, P> left = new Parameter<Object, P>(Optional.of("name"), type, annotations, Optional.of(entity));
|
||||
Parameter<String, P> right = new Parameter<String, P>(Optional.of("name"), ClassTypeInformation.from(String.class),
|
||||
annotations, Optional.of(stringEntity));
|
||||
|
||||
assertThat(left, is(not(right)));
|
||||
assertThat(left).isNotEqualTo(right);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Some test methods that define expected behaviour for {@link PersistentEntity} interface. Implementation test classes
|
||||
@@ -27,6 +26,6 @@ import static org.junit.Assert.*;
|
||||
public abstract class PersistentEntitySpec {
|
||||
|
||||
public static void assertInvariants(PersistentEntity<?, ?> entity) {
|
||||
assertThat(entity.getName(), is(notNullValue()));
|
||||
assertThat(entity.getName()).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
87
src/test/java/org/springframework/data/mapping/PreferredConstructorDiscovererUnitTests.java
Normal file → Executable file
87
src/test/java/org/springframework/data/mapping/PreferredConstructorDiscovererUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
@@ -38,52 +37,60 @@ public class PreferredConstructorDiscovererUnitTests<P extends PersistentPropert
|
||||
@Test
|
||||
public void findsNoArgConstructorForClassWithoutExplicitConstructor() {
|
||||
|
||||
PreferredConstructorDiscoverer<EntityWithoutConstructor, P> discoverer = new PreferredConstructorDiscoverer<EntityWithoutConstructor, P>(
|
||||
PreferredConstructorDiscoverer<EntityWithoutConstructor, P> discoverer = new PreferredConstructorDiscoverer<>(
|
||||
EntityWithoutConstructor.class);
|
||||
PreferredConstructor<EntityWithoutConstructor, P> constructor = discoverer.getConstructor();
|
||||
|
||||
assertThat(constructor, is(notNullValue()));
|
||||
assertThat(constructor.isNoArgConstructor(), is(true));
|
||||
assertThat(constructor.isExplicitlyAnnotated(), is(false));
|
||||
assertThat(discoverer.getConstructor()).hasValueSatisfying(constructor -> {
|
||||
|
||||
assertThat(constructor).isNotNull();
|
||||
assertThat(constructor.isNoArgConstructor()).isTrue();
|
||||
assertThat(constructor.isExplicitlyAnnotated()).isFalse();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findsNoArgConstructorForClassWithMultipleConstructorsAndNoArgOne() {
|
||||
|
||||
PreferredConstructorDiscoverer<ClassWithEmptyConstructor, P> discoverer = new PreferredConstructorDiscoverer<ClassWithEmptyConstructor, P>(
|
||||
PreferredConstructorDiscoverer<ClassWithEmptyConstructor, P> discoverer = new PreferredConstructorDiscoverer<>(
|
||||
ClassWithEmptyConstructor.class);
|
||||
PreferredConstructor<ClassWithEmptyConstructor, P> constructor = discoverer.getConstructor();
|
||||
|
||||
assertThat(constructor, is(notNullValue()));
|
||||
assertThat(constructor.isNoArgConstructor(), is(true));
|
||||
assertThat(constructor.isExplicitlyAnnotated(), is(false));
|
||||
assertThat(discoverer.getConstructor()).hasValueSatisfying(constructor -> {
|
||||
|
||||
assertThat(constructor).isNotNull();
|
||||
assertThat(constructor.isNoArgConstructor()).isTrue();
|
||||
assertThat(constructor.isExplicitlyAnnotated()).isFalse();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doesNotThrowExceptionForMultipleConstructorsAndNoNoArgConstructorWithoutAnnotation() {
|
||||
|
||||
PreferredConstructorDiscoverer<ClassWithMultipleConstructorsWithoutEmptyOne, P> discoverer = new PreferredConstructorDiscoverer<ClassWithMultipleConstructorsWithoutEmptyOne, P>(
|
||||
PreferredConstructorDiscoverer<ClassWithMultipleConstructorsWithoutEmptyOne, P> discoverer = new PreferredConstructorDiscoverer<>(
|
||||
ClassWithMultipleConstructorsWithoutEmptyOne.class);
|
||||
assertThat(discoverer.getConstructor(), is(nullValue()));
|
||||
|
||||
assertThat(discoverer.getConstructor()).isNotPresent();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usesConstructorWithAnnotationOverEveryOther() {
|
||||
|
||||
PreferredConstructorDiscoverer<ClassWithMultipleConstructorsAndAnnotation, P> discoverer = new PreferredConstructorDiscoverer<ClassWithMultipleConstructorsAndAnnotation, P>(
|
||||
PreferredConstructorDiscoverer<ClassWithMultipleConstructorsAndAnnotation, P> discoverer = new PreferredConstructorDiscoverer<>(
|
||||
ClassWithMultipleConstructorsAndAnnotation.class);
|
||||
PreferredConstructor<ClassWithMultipleConstructorsAndAnnotation, P> constructor = discoverer.getConstructor();
|
||||
|
||||
assertThat(constructor, is(notNullValue()));
|
||||
assertThat(constructor.isNoArgConstructor(), is(false));
|
||||
assertThat(constructor.isExplicitlyAnnotated(), is(true));
|
||||
assertThat(discoverer.getConstructor()).hasValueSatisfying(constructor -> {
|
||||
|
||||
assertThat(constructor.hasParameters(), is(true));
|
||||
Iterator<Parameter<Object, P>> parameters = constructor.getParameters().iterator();
|
||||
assertThat(constructor).isNotNull();
|
||||
assertThat(constructor.isNoArgConstructor()).isFalse();
|
||||
assertThat(constructor.isExplicitlyAnnotated()).isTrue();
|
||||
|
||||
Parameter<?, P> parameter = parameters.next();
|
||||
assertThat(parameter.getType().getType(), typeCompatibleWith(Long.class));
|
||||
assertThat(parameters.hasNext(), is(false));
|
||||
assertThat(constructor.hasParameters()).isTrue();
|
||||
|
||||
Iterator<Parameter<Object, P>> parameters = constructor.getParameters().iterator();
|
||||
|
||||
Parameter<?, P> parameter = parameters.next();
|
||||
assertThat(parameter.getType().getType()).isEqualTo(Long.class);
|
||||
assertThat(parameters.hasNext()).isFalse();
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-134
|
||||
@@ -91,10 +98,12 @@ public class PreferredConstructorDiscovererUnitTests<P extends PersistentPropert
|
||||
|
||||
PersistentEntity<Inner, P> entity = new BasicPersistentEntity<Inner, P>(ClassTypeInformation.from(Inner.class));
|
||||
PreferredConstructorDiscoverer<Inner, P> discoverer = new PreferredConstructorDiscoverer<Inner, P>(entity);
|
||||
PreferredConstructor<Inner, P> constructor = discoverer.getConstructor();
|
||||
|
||||
Parameter<?, P> parameter = constructor.getParameters().iterator().next();
|
||||
assertThat(constructor.isEnclosingClassParameter(parameter), is(true));
|
||||
assertThat(discoverer.getConstructor()).hasValueSatisfying(constructor -> {
|
||||
|
||||
Parameter<?, P> parameter = constructor.getParameters().iterator().next();
|
||||
assertThat(constructor.isEnclosingClassParameter(parameter)).isTrue();
|
||||
});
|
||||
}
|
||||
|
||||
static class EntityWithoutConstructor {
|
||||
@@ -103,39 +112,31 @@ public class PreferredConstructorDiscovererUnitTests<P extends PersistentPropert
|
||||
|
||||
static class ClassWithEmptyConstructor {
|
||||
|
||||
public ClassWithEmptyConstructor() {
|
||||
}
|
||||
public ClassWithEmptyConstructor() {}
|
||||
}
|
||||
|
||||
static class ClassWithMultipleConstructorsAndEmptyOne {
|
||||
|
||||
public ClassWithMultipleConstructorsAndEmptyOne(String value) {
|
||||
}
|
||||
public ClassWithMultipleConstructorsAndEmptyOne(String value) {}
|
||||
|
||||
public ClassWithMultipleConstructorsAndEmptyOne() {
|
||||
}
|
||||
public ClassWithMultipleConstructorsAndEmptyOne() {}
|
||||
}
|
||||
|
||||
static class ClassWithMultipleConstructorsWithoutEmptyOne {
|
||||
|
||||
public ClassWithMultipleConstructorsWithoutEmptyOne(String value) {
|
||||
}
|
||||
public ClassWithMultipleConstructorsWithoutEmptyOne(String value) {}
|
||||
|
||||
public ClassWithMultipleConstructorsWithoutEmptyOne(Long value) {
|
||||
}
|
||||
public ClassWithMultipleConstructorsWithoutEmptyOne(Long value) {}
|
||||
}
|
||||
|
||||
static class ClassWithMultipleConstructorsAndAnnotation {
|
||||
|
||||
public ClassWithMultipleConstructorsAndAnnotation() {
|
||||
}
|
||||
public ClassWithMultipleConstructorsAndAnnotation() {}
|
||||
|
||||
public ClassWithMultipleConstructorsAndAnnotation(String value) {
|
||||
}
|
||||
public ClassWithMultipleConstructorsAndAnnotation(String value) {}
|
||||
|
||||
@PersistenceConstructor
|
||||
public ClassWithMultipleConstructorsAndAnnotation(Long value) {
|
||||
}
|
||||
public ClassWithMultipleConstructorsAndAnnotation(Long value) {}
|
||||
}
|
||||
|
||||
static class Outer {
|
||||
|
||||
169
src/test/java/org/springframework/data/mapping/PropertyPathUnitTests.java
Normal file → Executable file
169
src/test/java/org/springframework/data/mapping/PropertyPathUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.mapping.PropertyPath.*;
|
||||
|
||||
import java.util.Iterator;
|
||||
@@ -40,78 +39,78 @@ public class PropertyPathUnitTests {
|
||||
@Rule public ExpectedException exception = ExpectedException.none();
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("rawtypes")
|
||||
public void parsesSimplePropertyCorrectly() throws Exception {
|
||||
|
||||
PropertyPath reference = PropertyPath.from("userName", Foo.class);
|
||||
assertThat(reference.hasNext(), is(false));
|
||||
assertThat(reference.toDotPath(), is("userName"));
|
||||
assertThat(reference.getOwningType(), is((TypeInformation) ClassTypeInformation.from(Foo.class)));
|
||||
|
||||
assertThat(reference.hasNext()).isFalse();
|
||||
assertThat(reference.toDotPath()).isEqualTo("userName");
|
||||
assertThat(reference.getOwningType()).isEqualTo(ClassTypeInformation.from(Foo.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parsesPathPropertyCorrectly() throws Exception {
|
||||
|
||||
PropertyPath reference = PropertyPath.from("userName", Bar.class);
|
||||
assertThat(reference.hasNext(), is(true));
|
||||
assertThat(reference.next(), is(new PropertyPath("name", FooBar.class)));
|
||||
assertThat(reference.toDotPath(), is("user.name"));
|
||||
assertThat(reference.hasNext()).isTrue();
|
||||
assertThat(reference.next()).isEqualTo(new PropertyPath("name", FooBar.class));
|
||||
assertThat(reference.toDotPath()).isEqualTo("user.name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void prefersLongerMatches() throws Exception {
|
||||
|
||||
PropertyPath reference = PropertyPath.from("userName", Sample.class);
|
||||
assertThat(reference.hasNext(), is(false));
|
||||
assertThat(reference.toDotPath(), is("userName"));
|
||||
assertThat(reference.hasNext()).isFalse();
|
||||
assertThat(reference.toDotPath()).isEqualTo("userName");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testname() throws Exception {
|
||||
|
||||
PropertyPath reference = PropertyPath.from("userName", Sample2.class);
|
||||
assertThat(reference.getSegment(), is("user"));
|
||||
assertThat(reference.hasNext(), is(true));
|
||||
assertThat(reference.next(), is(new PropertyPath("name", FooBar.class)));
|
||||
assertThat(reference.getSegment()).isEqualTo("user");
|
||||
assertThat(reference.hasNext()).isTrue();
|
||||
assertThat(reference.next()).isEqualTo(new PropertyPath("name", FooBar.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void prefersExplicitPaths() throws Exception {
|
||||
|
||||
PropertyPath reference = PropertyPath.from("user_name", Sample.class);
|
||||
assertThat(reference.getSegment(), is("user"));
|
||||
assertThat(reference.hasNext(), is(true));
|
||||
assertThat(reference.next(), is(new PropertyPath("name", FooBar.class)));
|
||||
assertThat(reference.getSegment()).isEqualTo("user");
|
||||
assertThat(reference.hasNext()).isTrue();
|
||||
assertThat(reference.next()).isEqualTo(new PropertyPath("name", FooBar.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlesGenericsCorrectly() throws Exception {
|
||||
|
||||
PropertyPath reference = PropertyPath.from("usersName", Bar.class);
|
||||
assertThat(reference.getSegment(), is("users"));
|
||||
assertThat(reference.isCollection(), is(true));
|
||||
assertThat(reference.hasNext(), is(true));
|
||||
assertThat(reference.next(), is(new PropertyPath("name", FooBar.class)));
|
||||
assertThat(reference.getSegment()).isEqualTo("users");
|
||||
assertThat(reference.isCollection()).isTrue();
|
||||
assertThat(reference.hasNext()).isTrue();
|
||||
assertThat(reference.next()).isEqualTo(new PropertyPath("name", FooBar.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlesMapCorrectly() throws Exception {
|
||||
|
||||
PropertyPath reference = PropertyPath.from("userMapName", Bar.class);
|
||||
assertThat(reference.getSegment(), is("userMap"));
|
||||
assertThat(reference.isCollection(), is(false));
|
||||
assertThat(reference.hasNext(), is(true));
|
||||
assertThat(reference.next(), is(new PropertyPath("name", FooBar.class)));
|
||||
assertThat(reference.getSegment()).isEqualTo("userMap");
|
||||
assertThat(reference.isCollection()).isFalse();
|
||||
assertThat(reference.hasNext()).isTrue();
|
||||
assertThat(reference.next()).isEqualTo(new PropertyPath("name", FooBar.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlesArrayCorrectly() throws Exception {
|
||||
|
||||
PropertyPath reference = PropertyPath.from("userArrayName", Bar.class);
|
||||
assertThat(reference.getSegment(), is("userArray"));
|
||||
assertThat(reference.isCollection(), is(true));
|
||||
assertThat(reference.hasNext(), is(true));
|
||||
assertThat(reference.next(), is(new PropertyPath("name", FooBar.class)));
|
||||
assertThat(reference.getSegment()).isEqualTo("userArray");
|
||||
assertThat(reference.isCollection()).isTrue();
|
||||
assertThat(reference.hasNext()).isTrue();
|
||||
assertThat(reference.next()).isEqualTo(new PropertyPath("name", FooBar.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -121,21 +120,18 @@ public class PropertyPathUnitTests {
|
||||
PropertyPath.from("usersMame", Bar.class);
|
||||
fail("Expected PropertyReferenceException!");
|
||||
} catch (PropertyReferenceException e) {
|
||||
assertThat(e.getPropertyName(), is("mame"));
|
||||
assertThat(e.getBaseProperty(), is(PropertyPath.from("users", Bar.class)));
|
||||
assertThat(e.getPropertyName()).isEqualTo("mame");
|
||||
assertThat(e.getBaseProperty()).isEqualTo(PropertyPath.from("users", Bar.class));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlesInvalidMapValueTypeProperly() {
|
||||
|
||||
try {
|
||||
PropertyPath.from("userMapMame", Bar.class);
|
||||
fail();
|
||||
} catch (PropertyReferenceException e) {
|
||||
assertThat(e.getPropertyName(), is("mame"));
|
||||
assertThat(e.getBaseProperty(), is(PropertyPath.from("userMap", Bar.class)));
|
||||
}
|
||||
assertThatExceptionOfType(PropertyReferenceException.class)//
|
||||
.isThrownBy(() -> PropertyPath.from("userMapMame", Bar.class))//
|
||||
.matches(e -> e.getPropertyName().equals("mame"))//
|
||||
.matches(e -> e.getBaseProperty().equals(PropertyPath.from("userMap", Bar.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -143,19 +139,19 @@ public class PropertyPathUnitTests {
|
||||
|
||||
PropertyPath from = PropertyPath.from("barUserName", Sample.class);
|
||||
|
||||
assertThat(from, is(notNullValue()));
|
||||
assertThat(from.getLeafProperty(), is(PropertyPath.from("name", FooBar.class)));
|
||||
assertThat(from).isNotNull();
|
||||
assertThat(from.getLeafProperty()).isEqualTo(PropertyPath.from("name", FooBar.class));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-45
|
||||
public void handlesEmptyUnderscoresCorrectly() {
|
||||
|
||||
PropertyPath propertyPath = PropertyPath.from("_foo", Sample2.class);
|
||||
assertThat(propertyPath.getSegment(), is("_foo"));
|
||||
assertThat(propertyPath.getType(), is(typeCompatibleWith(Foo.class)));
|
||||
assertThat(propertyPath.getSegment()).isEqualTo("_foo");
|
||||
assertThat(propertyPath.getType()).isEqualTo(Foo.class);
|
||||
|
||||
propertyPath = PropertyPath.from("_foo__email", Sample2.class);
|
||||
assertThat(propertyPath.toDotPath(), is("_foo._email"));
|
||||
assertThat(propertyPath.toDotPath()).isEqualTo("_foo._email");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -163,9 +159,9 @@ public class PropertyPathUnitTests {
|
||||
|
||||
PropertyPath propertyPath = PropertyPath.from("bar.userMap.name", Sample.class);
|
||||
|
||||
assertThat(propertyPath, is(notNullValue()));
|
||||
assertThat(propertyPath.getSegment(), is("bar"));
|
||||
assertThat(propertyPath.getLeafProperty(), is(PropertyPath.from("name", FooBar.class)));
|
||||
assertThat(propertyPath).isNotNull();
|
||||
assertThat(propertyPath.getSegment()).isEqualTo("bar");
|
||||
assertThat(propertyPath.getLeafProperty()).isEqualTo(PropertyPath.from("name", FooBar.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -174,9 +170,9 @@ public class PropertyPathUnitTests {
|
||||
PropertyPath propertyPath = PropertyPath.from("userName", Foo.class);
|
||||
|
||||
Iterator<PropertyPath> iterator = propertyPath.iterator();
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(propertyPath));
|
||||
assertThat(iterator.hasNext(), is(false));
|
||||
assertThat(iterator.hasNext()).isTrue();
|
||||
assertThat(iterator.next()).isEqualTo(propertyPath);
|
||||
assertThat(iterator.hasNext()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -185,41 +181,35 @@ public class PropertyPathUnitTests {
|
||||
PropertyPath propertyPath = PropertyPath.from("user.name", Bar.class);
|
||||
|
||||
Iterator<PropertyPath> iterator = propertyPath.iterator();
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(propertyPath));
|
||||
assertThat(iterator.hasNext(), is(true));
|
||||
assertThat(iterator.next(), is(propertyPath.next()));
|
||||
assertThat(iterator.hasNext(), is(false));
|
||||
assertThat(iterator.hasNext()).isTrue();
|
||||
assertThat(iterator.next()).isEqualTo(propertyPath);
|
||||
assertThat(iterator.hasNext()).isTrue();
|
||||
assertThat(iterator.next()).isEqualTo(propertyPath.next());
|
||||
assertThat(iterator.hasNext()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-139
|
||||
public void rejectsInvalidPropertyWithLeadingUnderscore() {
|
||||
try {
|
||||
PropertyPath.from("_id", Foo.class);
|
||||
fail();
|
||||
} catch (PropertyReferenceException e) {
|
||||
assertThat(e.getMessage(), containsString("property _id"));
|
||||
}
|
||||
|
||||
assertThatExceptionOfType(PropertyReferenceException.class)//
|
||||
.isThrownBy(() -> PropertyPath.from("_id", Foo.class))//
|
||||
.withMessageContaining("property _id");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-139
|
||||
public void rejectsNestedInvalidPropertyWithLeadingUnderscore() {
|
||||
try {
|
||||
PropertyPath.from("_foo_id", Sample2.class);
|
||||
fail();
|
||||
} catch (PropertyReferenceException e) {
|
||||
assertThat(e.getMessage(), containsString("property id"));
|
||||
}
|
||||
|
||||
assertThatExceptionOfType(PropertyReferenceException.class)//
|
||||
.isThrownBy(() -> PropertyPath.from("_foo_id", Sample2.class))//
|
||||
.withMessageContaining("property id");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-139
|
||||
public void rejectsNestedInvalidPropertyExplictlySplitWithLeadingUnderscore() {
|
||||
try {
|
||||
PropertyPath.from("_foo__id", Sample2.class);
|
||||
fail();
|
||||
} catch (PropertyReferenceException e) {
|
||||
assertThat(e.getMessage(), containsString("property _id"));
|
||||
}
|
||||
|
||||
assertThatExceptionOfType(PropertyReferenceException.class)//
|
||||
.isThrownBy(() -> PropertyPath.from("_foo__id", Sample2.class))//
|
||||
.withMessageContaining("property _id");
|
||||
}
|
||||
|
||||
@Test(expected = PropertyReferenceException.class) // DATACMNS 158
|
||||
@@ -230,12 +220,9 @@ public class PropertyPathUnitTests {
|
||||
@Test
|
||||
public void rejectsInvalidProperty() {
|
||||
|
||||
try {
|
||||
PropertyPath.from("bar", Foo.class);
|
||||
fail();
|
||||
} catch (PropertyReferenceException e) {
|
||||
assertThat(e.getBaseProperty(), is(nullValue()));
|
||||
}
|
||||
assertThatExceptionOfType(PropertyReferenceException.class)//
|
||||
.isThrownBy(() -> PropertyPath.from("_foo_id", Sample2.class))//
|
||||
.matches(e -> e.getBaseProperty().getSegment().equals("_foo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -246,12 +233,12 @@ public class PropertyPathUnitTests {
|
||||
|
||||
PropertyPath shortPath = PropertyPath.from("user", Bar.class);
|
||||
|
||||
assertThat(left, is(right));
|
||||
assertThat(right, is(left));
|
||||
assertThat(left, is(not(shortPath)));
|
||||
assertThat(shortPath, is(not(left)));
|
||||
assertThat(left).isEqualTo(right);
|
||||
assertThat(right).isEqualTo(left);
|
||||
assertThat(left).isNotEqualTo(shortPath);
|
||||
assertThat(shortPath).isNotEqualTo(left);
|
||||
|
||||
assertThat(left, is(not(new Object())));
|
||||
assertThat(left).isNotEqualTo(new Object());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -262,8 +249,8 @@ public class PropertyPathUnitTests {
|
||||
|
||||
PropertyPath shortPath = PropertyPath.from("user", Bar.class);
|
||||
|
||||
assertThat(left.hashCode(), is(right.hashCode()));
|
||||
assertThat(left.hashCode(), is(not(shortPath.hashCode())));
|
||||
assertThat(left.hashCode()).isEqualTo(right.hashCode());
|
||||
assertThat(left.hashCode()).isNotEqualTo(shortPath.hashCode());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-257
|
||||
@@ -271,8 +258,8 @@ public class PropertyPathUnitTests {
|
||||
|
||||
PropertyPath path = PropertyPath.from("UUID", Foo.class);
|
||||
|
||||
assertThat(path, is(notNullValue()));
|
||||
assertThat(path.getSegment(), is("UUID"));
|
||||
assertThat(path).isNotNull();
|
||||
assertThat(path.getSegment()).isEqualTo("UUID");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-257
|
||||
@@ -280,10 +267,10 @@ public class PropertyPathUnitTests {
|
||||
|
||||
PropertyPath path = PropertyPath.from("_fooUUID", Sample2.class);
|
||||
|
||||
assertThat(path, is(notNullValue()));
|
||||
assertThat(path.getSegment(), is("_foo"));
|
||||
assertThat(path.hasNext(), is(true));
|
||||
assertThat(path.next().getSegment(), is("UUID"));
|
||||
assertThat(path).isNotNull();
|
||||
assertThat(path.getSegment()).isEqualTo("_foo");
|
||||
assertThat(path.hasNext()).isTrue();
|
||||
assertThat(path.next().getSegment()).isEqualTo("UUID");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-381
|
||||
|
||||
6
src/test/java/org/springframework/data/mapping/PropertyReferenceExceptionUnitTests.java
Normal file → Executable file
6
src/test/java/org/springframework/data/mapping/PropertyReferenceExceptionUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
@@ -74,8 +73,7 @@ public class PropertyReferenceExceptionUnitTests {
|
||||
|
||||
Collection<String> matches = exception.getPropertyMatches();
|
||||
|
||||
assertThat(matches, hasSize(1));
|
||||
assertThat(matches, hasItem("name"));
|
||||
assertThat(matches).containsExactly("name");
|
||||
}
|
||||
|
||||
static class Sample {
|
||||
|
||||
27
src/test/java/org/springframework/data/mapping/SimpleTypeHolderUnitTests.java
Normal file → Executable file
27
src/test/java/org/springframework/data/mapping/SimpleTypeHolderUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.mapping;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.Collections;
|
||||
@@ -54,7 +53,7 @@ public class SimpleTypeHolderUnitTests {
|
||||
|
||||
SimpleTypeHolder holder = new SimpleTypeHolder();
|
||||
|
||||
assertThat(holder.isSimpleType(String.class), is(true));
|
||||
assertThat(holder.isSimpleType(String.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -62,7 +61,7 @@ public class SimpleTypeHolderUnitTests {
|
||||
|
||||
SimpleTypeHolder holder = new SimpleTypeHolder(new HashSet<Class<?>>(), false);
|
||||
|
||||
assertThat(holder.isSimpleType(UUID.class), is(false));
|
||||
assertThat(holder.isSimpleType(UUID.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -70,8 +69,8 @@ public class SimpleTypeHolderUnitTests {
|
||||
|
||||
SimpleTypeHolder holder = new SimpleTypeHolder(Collections.singleton(SimpleTypeHolder.class), true);
|
||||
|
||||
assertThat(holder.isSimpleType(SimpleTypeHolder.class), is(true));
|
||||
assertThat(holder.isSimpleType(SimpleTypeHolderUnitTests.class), is(false));
|
||||
assertThat(holder.isSimpleType(SimpleTypeHolder.class)).isTrue();
|
||||
assertThat(holder.isSimpleType(SimpleTypeHolderUnitTests.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -80,30 +79,30 @@ public class SimpleTypeHolderUnitTests {
|
||||
SimpleTypeHolder holder = new SimpleTypeHolder(Collections.singleton(SimpleTypeHolder.class), true);
|
||||
SimpleTypeHolder second = new SimpleTypeHolder(Collections.singleton(SimpleTypeHolderUnitTests.class), holder);
|
||||
|
||||
assertThat(holder.isSimpleType(SimpleTypeHolder.class), is(true));
|
||||
assertThat(holder.isSimpleType(SimpleTypeHolderUnitTests.class), is(false));
|
||||
assertThat(second.isSimpleType(SimpleTypeHolder.class), is(true));
|
||||
assertThat(second.isSimpleType(SimpleTypeHolderUnitTests.class), is(true));
|
||||
assertThat(holder.isSimpleType(SimpleTypeHolder.class)).isTrue();
|
||||
assertThat(holder.isSimpleType(SimpleTypeHolderUnitTests.class)).isFalse();
|
||||
assertThat(second.isSimpleType(SimpleTypeHolder.class)).isTrue();
|
||||
assertThat(second.isSimpleType(SimpleTypeHolderUnitTests.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void considersObjectToBeSimpleType() {
|
||||
SimpleTypeHolder holder = new SimpleTypeHolder();
|
||||
assertThat(holder.isSimpleType(Object.class), is(true));
|
||||
assertThat(holder.isSimpleType(Object.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void considersSimpleEnumAsSimple() {
|
||||
|
||||
SimpleTypeHolder holder = new SimpleTypeHolder();
|
||||
assertThat(holder.isSimpleType(SimpleEnum.FOO.getClass()), is(true));
|
||||
assertThat(holder.isSimpleType(SimpleEnum.FOO.getClass())).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void considersComplexEnumAsSimple() {
|
||||
|
||||
SimpleTypeHolder holder = new SimpleTypeHolder();
|
||||
assertThat(holder.isSimpleType(ComplexEnum.FOO.getClass()), is(true));
|
||||
assertThat(holder.isSimpleType(ComplexEnum.FOO.getClass())).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-1006
|
||||
@@ -111,7 +110,7 @@ public class SimpleTypeHolderUnitTests {
|
||||
|
||||
SimpleTypeHolder holder = new SimpleTypeHolder();
|
||||
|
||||
assertThat(holder.isSimpleType(Type.class), is(true));
|
||||
assertThat(holder.isSimpleType(Type.class)).isTrue();
|
||||
}
|
||||
|
||||
enum SimpleEnum {
|
||||
|
||||
16
src/test/java/org/springframework/data/mapping/context/AbstractMappingContextIntegrationTests.java
Normal file → Executable file
16
src/test/java/org/springframework/data/mapping/context/AbstractMappingContextIntegrationTests.java
Normal file → Executable file
@@ -15,13 +15,13 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.context;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.annotation.Id;
|
||||
@@ -47,7 +47,7 @@ public class AbstractMappingContextIntegrationTests<T extends PersistentProperty
|
||||
context.setInitialEntitySet(Collections.singleton(Person.class));
|
||||
context.initialize();
|
||||
|
||||
assertThat(context.getManagedTypes(), hasItem(ClassTypeInformation.from(Person.class)));
|
||||
assertThat(context.getManagedTypes()).contains(ClassTypeInformation.from(Person.class));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-457
|
||||
@@ -57,7 +57,7 @@ public class AbstractMappingContextIntegrationTests<T extends PersistentProperty
|
||||
context.setInitialEntitySet(Collections.singleton(Person.class));
|
||||
context.initialize();
|
||||
|
||||
assertThat(context.hasPersistentEntityFor(Person.class), is(true));
|
||||
assertThat(context.hasPersistentEntityFor(Person.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-243
|
||||
@@ -66,7 +66,7 @@ public class AbstractMappingContextIntegrationTests<T extends PersistentProperty
|
||||
SampleMappingContext context = new SampleMappingContext();
|
||||
PersistentEntity<Object, SamplePersistentProperty> entity = context.getPersistentEntity(InterfaceOnly.class);
|
||||
|
||||
assertThat(entity.getIdProperty(), is(notNullValue()));
|
||||
assertThat(entity.getIdProperty()).isNotNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-65
|
||||
@@ -116,13 +116,13 @@ public class AbstractMappingContextIntegrationTests<T extends PersistentProperty
|
||||
|
||||
@Override
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
protected T createPersistentProperty(final Field field, final PropertyDescriptor descriptor,
|
||||
final BasicPersistentEntity<Object, T> owner, final SimpleTypeHolder simpleTypeHolder) {
|
||||
protected T createPersistentProperty(Optional<Field> field, PropertyDescriptor descriptor,
|
||||
final BasicPersistentEntity<Object, T> owner, SimpleTypeHolder simpleTypeHolder) {
|
||||
|
||||
PersistentProperty prop = mock(PersistentProperty.class);
|
||||
|
||||
when(prop.getTypeInformation()).thenReturn(owner.getTypeInformation());
|
||||
when(prop.getName()).thenReturn(field == null ? descriptor.getName() : field.getName());
|
||||
when(prop.getName()).thenReturn(field.map(Field::getName).orElse(descriptor.getName()));
|
||||
when(prop.getPersistentEntityType()).thenReturn(Collections.EMPTY_SET);
|
||||
|
||||
try {
|
||||
|
||||
59
src/test/java/org/springframework/data/mapping/context/AbstractMappingContextUnitTests.java
Normal file → Executable file
59
src/test/java/org/springframework/data/mapping/context/AbstractMappingContextUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.context;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import groovy.lang.MetaClass;
|
||||
@@ -26,7 +25,6 @@ import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
@@ -40,6 +38,7 @@ import org.springframework.data.mapping.model.MappingException;
|
||||
import org.springframework.data.mapping.model.SimpleTypeHolder;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
import org.springframework.data.util.TypeInformation;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* Unit test for {@link AbstractMappingContext}.
|
||||
@@ -62,7 +61,7 @@ public class AbstractMappingContextUnitTests {
|
||||
public void doesNotTryToLookupPersistentEntityForLeafProperty() {
|
||||
PersistentPropertyPath<SamplePersistentProperty> path = context
|
||||
.getPersistentPropertyPath(PropertyPath.from("name", Person.class));
|
||||
assertThat(path, is(notNullValue()));
|
||||
assertThat(path).isNotNull();
|
||||
}
|
||||
|
||||
@Test(expected = MappingException.class) // DATACMNS-92
|
||||
@@ -112,7 +111,7 @@ public class AbstractMappingContextUnitTests {
|
||||
public void returnsNullPersistentEntityForSimpleTypes() {
|
||||
|
||||
SampleMappingContext context = new SampleMappingContext();
|
||||
assertThat(context.getPersistentEntity(String.class), is(nullValue()));
|
||||
assertThat(context.getPersistentEntity(String.class)).isNull();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class) // DATACMNS-214
|
||||
@@ -132,7 +131,7 @@ public class AbstractMappingContextUnitTests {
|
||||
mappingContext.initialize();
|
||||
|
||||
PersistentEntity<Object, SamplePersistentProperty> entity = mappingContext.getPersistentEntity(Sample.class);
|
||||
assertThat(entity.getPersistentProperty("metaClass"), is(nullValue()));
|
||||
assertThat(entity.getPersistentProperty("metaClass")).isNotPresent();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-332
|
||||
@@ -140,7 +139,10 @@ public class AbstractMappingContextUnitTests {
|
||||
|
||||
SampleMappingContext mappingContext = new SampleMappingContext();
|
||||
PersistentEntity<Object, SamplePersistentProperty> entity = mappingContext.getPersistentEntity(Extension.class);
|
||||
assertThat(entity.getPersistentProperty("foo").isIdProperty(), is(true));
|
||||
|
||||
assertThat(entity.getPersistentProperty("foo")).hasValueSatisfying(it -> {
|
||||
assertThat(it.isIdProperty()).isTrue();
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-345
|
||||
@@ -149,11 +151,15 @@ public class AbstractMappingContextUnitTests {
|
||||
|
||||
SampleMappingContext mappingContext = new SampleMappingContext();
|
||||
PersistentEntity<Object, SamplePersistentProperty> entity = mappingContext.getPersistentEntity(Sample.class);
|
||||
SamplePersistentProperty property = entity.getPersistentProperty("persons");
|
||||
PersistentEntity<Object, SamplePersistentProperty> propertyEntity = mappingContext.getPersistentEntity(property);
|
||||
|
||||
assertThat(propertyEntity, is(notNullValue()));
|
||||
assertThat(propertyEntity.getType(), is(equalTo((Class) Person.class)));
|
||||
assertThat(entity.getPersistentProperty("persons")).hasValueSatisfying(it -> {
|
||||
|
||||
PersistentEntity<Object, SamplePersistentProperty> propertyEntity = mappingContext.getPersistentEntity(it);
|
||||
|
||||
assertThat(propertyEntity).isNotNull();
|
||||
assertThat(propertyEntity.getType()).isEqualTo(Person.class);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Test // DATACMNS-380
|
||||
@@ -162,9 +168,9 @@ public class AbstractMappingContextUnitTests {
|
||||
PersistentPropertyPath<SamplePersistentProperty> path = context.getPersistentPropertyPath("persons.name",
|
||||
Sample.class);
|
||||
|
||||
assertThat(path.getLength(), is(2));
|
||||
assertThat(path.getBaseProperty().getName(), is("persons"));
|
||||
assertThat(path.getLeafProperty().getName(), is("name"));
|
||||
assertThat(path.getLength()).isEqualTo(2);
|
||||
assertThat(path.getBaseProperty().getName()).isEqualTo("persons");
|
||||
assertThat(path.getLeafProperty().getName()).isEqualTo("name");
|
||||
}
|
||||
|
||||
@Test(expected = MappingException.class) // DATACMNS-380
|
||||
@@ -191,7 +197,7 @@ public class AbstractMappingContextUnitTests {
|
||||
public void shouldReturnNullForSimpleTypesIfInStrictIsEnabled() {
|
||||
|
||||
context.setStrict(true);
|
||||
assertThat(context.getPersistentEntity(Integer.class), is(nullValue()));
|
||||
assertThat(context.getPersistentEntity(Integer.class)).isNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-462
|
||||
@@ -210,27 +216,18 @@ public class AbstractMappingContextUnitTests {
|
||||
|
||||
@Test // DATACMNS-695
|
||||
public void persistentPropertyPathTraversesGenericTypesCorrectly() {
|
||||
assertThat(context.getPersistentPropertyPath("field.wrapped.field", Outer.class),
|
||||
is(Matchers.<SamplePersistentProperty> iterableWithSize(3)));
|
||||
assertThat(context.getPersistentPropertyPath("field.wrapped.field", Outer.class)).hasSize(3);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-727
|
||||
public void exposesContextForFailingPropertyPathLookup() {
|
||||
|
||||
try {
|
||||
|
||||
context.getPersistentPropertyPath("persons.firstname", Sample.class);
|
||||
fail("Expected InvalidPersistentPropertyPath!");
|
||||
|
||||
} catch (InvalidPersistentPropertyPath o_O) {
|
||||
|
||||
assertThat(o_O.getMessage(), not(isEmptyOrNullString()));
|
||||
assertThat(o_O.getResolvedPath(), is("persons"));
|
||||
assertThat(o_O.getUnresolvableSegment(), is("firstname"));
|
||||
|
||||
// Make sure, the resolvable part can be obtained
|
||||
assertThat(context.getPersistentPropertyPath(o_O), is(notNullValue()));
|
||||
}
|
||||
assertThatExceptionOfType(InvalidPersistentPropertyPath.class)//
|
||||
.isThrownBy(() -> context.getPersistentPropertyPath("persons.firstname", Sample.class))//
|
||||
.matches(e -> StringUtils.hasText(e.getMessage()))//
|
||||
.matches(e -> e.getResolvedPath().equals("persons"))//
|
||||
.matches(e -> e.getUnresolvableSegment().equals("firstname"))//
|
||||
.matches(e -> context.getPersistentPropertyPath(e) != null);
|
||||
}
|
||||
|
||||
private static void assertHasEntityFor(Class<?> type, SampleMappingContext context, boolean expected) {
|
||||
|
||||
64
src/test/java/org/springframework/data/mapping/context/DefaultPersistenPropertyPathUnitTests.java
Normal file → Executable file
64
src/test/java/org/springframework/data/mapping/context/DefaultPersistenPropertyPathUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.context;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -46,15 +45,14 @@ public class DefaultPersistenPropertyPathUnitTests<T extends PersistentProperty<
|
||||
PersistentPropertyPath<T> twoLegs;
|
||||
|
||||
@Before
|
||||
@SuppressWarnings("unchecked")
|
||||
public void setUp() {
|
||||
oneLeg = new DefaultPersistentPropertyPath<T>(Arrays.asList(first));
|
||||
twoLegs = new DefaultPersistentPropertyPath<T>(Arrays.asList(first, second));
|
||||
oneLeg = new DefaultPersistentPropertyPath<>(Arrays.asList(first));
|
||||
twoLegs = new DefaultPersistentPropertyPath<>(Arrays.asList(first, second));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void rejectsNullProperties() {
|
||||
new DefaultPersistentPropertyPath<T>(null);
|
||||
new DefaultPersistentPropertyPath<>(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -63,89 +61,69 @@ public class DefaultPersistenPropertyPathUnitTests<T extends PersistentProperty<
|
||||
when(first.getName()).thenReturn("foo");
|
||||
when(second.getName()).thenReturn("bar");
|
||||
|
||||
assertThat(twoLegs.toDotPath(), is("foo.bar"));
|
||||
assertThat(twoLegs.toDotPath()).isEqualTo("foo.bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void usesConverterToCreatePropertyPath() {
|
||||
|
||||
when(converter.convert((T) any())).thenReturn("foo");
|
||||
when(converter.convert(any())).thenReturn("foo");
|
||||
|
||||
assertThat(twoLegs.toDotPath(converter), is("foo.foo"));
|
||||
assertThat(twoLegs.toDotPath(converter)).isEqualTo("foo.foo");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsCorrectLeafProperty() {
|
||||
|
||||
assertThat(twoLegs.getLeafProperty(), is(second));
|
||||
assertThat(oneLeg.getLeafProperty(), is(first));
|
||||
assertThat(twoLegs.getLeafProperty()).isEqualTo(second);
|
||||
assertThat(oneLeg.getLeafProperty()).isEqualTo(first);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsCorrectBaseProperty() {
|
||||
|
||||
assertThat(twoLegs.getBaseProperty(), is(first));
|
||||
assertThat(oneLeg.getBaseProperty(), is(first));
|
||||
assertThat(twoLegs.getBaseProperty()).isEqualTo(first);
|
||||
assertThat(oneLeg.getBaseProperty()).isEqualTo(first);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void detectsBasePathCorrectly() {
|
||||
|
||||
assertThat(oneLeg.isBasePathOf(twoLegs), is(true));
|
||||
assertThat(twoLegs.isBasePathOf(oneLeg), is(false));
|
||||
assertThat(oneLeg.isBasePathOf(twoLegs)).isTrue();
|
||||
assertThat(twoLegs.isBasePathOf(oneLeg)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void calculatesExtensionCorrectly() {
|
||||
|
||||
PersistentPropertyPath<T> extension = twoLegs.getExtensionForBaseOf(oneLeg);
|
||||
assertThat(extension, is((PersistentPropertyPath<T>) new DefaultPersistentPropertyPath<T>(Arrays.asList(second))));
|
||||
|
||||
assertThat(extension).isEqualTo(new DefaultPersistentPropertyPath<>(Arrays.asList(second)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsTheCorrectParentPath() {
|
||||
assertThat(twoLegs.getParentPath(), is(oneLeg));
|
||||
assertThat(twoLegs.getParentPath()).isEqualTo(oneLeg);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsItselfAsParentPathIfSizeOne() {
|
||||
assertThat(oneLeg.getParentPath(), is(oneLeg));
|
||||
assertThat(oneLeg.getParentPath()).isEqualTo(oneLeg);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void pathReturnsCorrectSize() {
|
||||
assertThat(oneLeg.getLength(), is(1));
|
||||
assertThat(twoLegs.getLength(), is(2));
|
||||
assertThat(oneLeg.getLength()).isEqualTo(1);
|
||||
assertThat(twoLegs.getLength()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-444
|
||||
public void skipsMappedPropertyNameIfConverterReturnsNull() {
|
||||
|
||||
String result = twoLegs.toDotPath(new Converter<T, String>() {
|
||||
|
||||
@Override
|
||||
public String convert(T source) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
assertThat(result, is(nullValue()));
|
||||
assertThat(twoLegs.toDotPath(source -> null)).isNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-444
|
||||
public void skipsMappedPropertyNameIfConverterReturnsEmptyStrings() {
|
||||
|
||||
String result = twoLegs.toDotPath(new Converter<T, String>() {
|
||||
|
||||
@Override
|
||||
public String convert(T source) {
|
||||
return "";
|
||||
}
|
||||
});
|
||||
|
||||
assertThat(result, is(nullValue()));
|
||||
assertThat(twoLegs.toDotPath(source -> "")).isNull();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
13
src/test/java/org/springframework/data/mapping/context/MappingContextEventUnitTests.java
Normal file → Executable file
13
src/test/java/org/springframework/data/mapping/context/MappingContextEventUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.context;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
@@ -24,8 +23,6 @@ import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.mapping.PersistentProperty;
|
||||
import org.springframework.data.mapping.context.MappingContext;
|
||||
import org.springframework.data.mapping.context.MappingContextEvent;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link MappingContextEvent}.
|
||||
@@ -45,21 +42,21 @@ public class MappingContextEventUnitTests<E extends PersistentEntity<?, P>, P ex
|
||||
public void returnsPersistentEntityHandedToTheEvent() {
|
||||
|
||||
MappingContextEvent<E, P> event = new MappingContextEvent<E, P>(mappingContext, entity);
|
||||
assertThat(event.getPersistentEntity(), is(entity));
|
||||
assertThat(event.getPersistentEntity()).isEqualTo(entity);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usesMappingContextAsEventSource() {
|
||||
|
||||
MappingContextEvent<E, P> event = new MappingContextEvent<E, P>(mappingContext, entity);
|
||||
assertThat(event.getSource(), is((Object) mappingContext));
|
||||
assertThat(event.getSource()).isEqualTo(mappingContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void detectsEmittingMappingContextCorrectly() {
|
||||
|
||||
MappingContextEvent<E, P> event = new MappingContextEvent<E, P>(mappingContext, entity);
|
||||
assertThat(event.wasEmittedBy(mappingContext), is(true));
|
||||
assertThat(event.wasEmittedBy(otherMappingContext), is(false));
|
||||
assertThat(event.wasEmittedBy(mappingContext)).isTrue();
|
||||
assertThat(event.wasEmittedBy(otherMappingContext)).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
48
src/test/java/org/springframework/data/mapping/context/MappingContextIsNewStrategyFactoryUnitTests.java
Normal file → Executable file
48
src/test/java/org/springframework/data/mapping/context/MappingContextIsNewStrategyFactoryUnitTests.java
Normal file → Executable file
@@ -15,12 +15,12 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.context;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
@@ -45,7 +45,7 @@ public class MappingContextIsNewStrategyFactoryUnitTests {
|
||||
public void setUp() {
|
||||
|
||||
SampleMappingContext context = new SampleMappingContext();
|
||||
context.setInitialEntitySet(new HashSet<Class<?>>(Arrays.<Class<?>> asList(Entity.class, VersionedEntity.class)));
|
||||
context.setInitialEntitySet(new HashSet<>(Arrays.asList(Entity.class, VersionedEntity.class)));
|
||||
context.afterPropertiesSet();
|
||||
|
||||
factory = new MappingContextIsNewStrategyFactory(new PersistentEntities(Collections.singleton(context)));
|
||||
@@ -55,48 +55,48 @@ public class MappingContextIsNewStrategyFactoryUnitTests {
|
||||
public void returnsPropertyIsNullOrZeroIsNewStrategyForVersionedEntity() {
|
||||
|
||||
IsNewStrategy strategy = factory.getIsNewStrategy(VersionedEntity.class);
|
||||
assertThat(strategy, is(instanceOf(PropertyIsNullOrZeroNumberIsNewStrategy.class)));
|
||||
assertThat(strategy).isInstanceOf(PropertyIsNullOrZeroNumberIsNewStrategy.class);
|
||||
|
||||
VersionedEntity entity = new VersionedEntity();
|
||||
assertThat(strategy.isNew(entity), is(true));
|
||||
Optional<VersionedEntity> entity = Optional.of(new VersionedEntity());
|
||||
assertThat(strategy.isNew(entity)).isTrue();
|
||||
|
||||
entity.id = 1L;
|
||||
assertThat(strategy.isNew(entity), is(true));
|
||||
entity.get().id = 1L;
|
||||
assertThat(strategy.isNew(entity)).isTrue();
|
||||
|
||||
entity.version = 0L;
|
||||
assertThat(strategy.isNew(entity), is(true));
|
||||
entity.get().version = 0L;
|
||||
assertThat(strategy.isNew(entity)).isTrue();
|
||||
|
||||
entity.version = 1L;
|
||||
assertThat(strategy.isNew(entity), is(false));
|
||||
entity.get().version = 1L;
|
||||
assertThat(strategy.isNew(entity)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsPropertyIsNullOrZeroIsNewStrategyForPrimitiveVersionedEntity() {
|
||||
|
||||
IsNewStrategy strategy = factory.getIsNewStrategy(VersionedEntity.class);
|
||||
assertThat(strategy, is(instanceOf(PropertyIsNullOrZeroNumberIsNewStrategy.class)));
|
||||
assertThat(strategy).isInstanceOf(PropertyIsNullOrZeroNumberIsNewStrategy.class);
|
||||
|
||||
VersionedEntity entity = new VersionedEntity();
|
||||
assertThat(strategy.isNew(entity), is(true));
|
||||
Optional<VersionedEntity> entity = Optional.of(new VersionedEntity());
|
||||
assertThat(strategy.isNew(entity)).isTrue();
|
||||
|
||||
entity.id = 1L;
|
||||
assertThat(strategy.isNew(entity), is(true));
|
||||
entity.get().id = 1L;
|
||||
assertThat(strategy.isNew(entity)).isTrue();
|
||||
|
||||
entity.version = 1L;
|
||||
assertThat(strategy.isNew(entity), is(false));
|
||||
entity.get().version = 1L;
|
||||
assertThat(strategy.isNew(entity)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsPropertyIsNullIsNewStrategyForEntity() {
|
||||
|
||||
IsNewStrategy strategy = factory.getIsNewStrategy(Entity.class);
|
||||
assertThat(strategy, is(instanceOf(PropertyIsNullIsNewStrategy.class)));
|
||||
assertThat(strategy).isInstanceOf(PropertyIsNullIsNewStrategy.class);
|
||||
|
||||
Entity entity = new Entity();
|
||||
assertThat(strategy.isNew(entity), is(true));
|
||||
Optional<Entity> entity = Optional.of(new Entity());
|
||||
assertThat(strategy.isNew(entity)).isTrue();
|
||||
|
||||
entity.id = 1L;
|
||||
assertThat(strategy.isNew(entity), is(false));
|
||||
entity.get().id = 1L;
|
||||
assertThat(strategy.isNew(entity)).isFalse();
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
|
||||
11
src/test/java/org/springframework/data/mapping/context/PersistentEntitiesUnitTests.java
Normal file → Executable file
11
src/test/java/org/springframework/data/mapping/context/PersistentEntitiesUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.context;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
@@ -68,10 +67,10 @@ public class PersistentEntitiesUnitTests {
|
||||
|
||||
PersistentEntities entities = new PersistentEntities(Arrays.asList(context));
|
||||
|
||||
assertThat(entities.getPersistentEntity(Sample.class), is(notNullValue()));
|
||||
assertThat(entities.getPersistentEntity(Object.class), is(nullValue()));
|
||||
assertThat(entities.getManagedTypes(), hasItem(ClassTypeInformation.from(Sample.class)));
|
||||
assertThat(entities, hasItem(entities.getPersistentEntity(Sample.class)));
|
||||
assertThat(entities.getPersistentEntity(Sample.class)).isNotNull();
|
||||
assertThat(entities.getPersistentEntity(Object.class)).isNull();
|
||||
assertThat(entities.getManagedTypes()).contains(ClassTypeInformation.from(Sample.class));
|
||||
assertThat(entities).contains(entities.getPersistentEntity(Sample.class));
|
||||
}
|
||||
|
||||
static class Sample {
|
||||
|
||||
27
src/test/java/org/springframework/data/mapping/context/PropertyMatchUnitTests.java
Normal file → Executable file
27
src/test/java/org/springframework/data/mapping/context/PropertyMatchUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.context;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.mapping.context.AbstractMappingContext.PersistentPropertyFilter.PropertyMatch;
|
||||
@@ -38,36 +37,36 @@ public class PropertyMatchUnitTests {
|
||||
public void matchesFieldByConcreteNameAndType() throws Exception {
|
||||
|
||||
PropertyMatch match = new PropertyMatch("name", "java.lang.String");
|
||||
assertThat(match.matches("this$0", Object.class), is(false));
|
||||
assertThat(match.matches("this$1", Object.class), is(false));
|
||||
assertThat(match.matches("name", String.class), is(true));
|
||||
assertThat(match.matches("this$0", Object.class)).isFalse();
|
||||
assertThat(match.matches("this$1", Object.class)).isFalse();
|
||||
assertThat(match.matches("name", String.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesFieldByNamePattern() throws Exception {
|
||||
|
||||
PropertyMatch match = new PropertyMatch("this\\$.*", "java.lang.Object");
|
||||
assertThat(match.matches("this$0", Object.class), is(true));
|
||||
assertThat(match.matches("this$1", Object.class), is(true));
|
||||
assertThat(match.matches("name", String.class), is(false));
|
||||
assertThat(match.matches("this$0", Object.class)).isTrue();
|
||||
assertThat(match.matches("this$1", Object.class)).isTrue();
|
||||
assertThat(match.matches("name", String.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesFieldByNameOnly() throws Exception {
|
||||
|
||||
PropertyMatch match = new PropertyMatch("this\\$.*", null);
|
||||
assertThat(match.matches("this$0", Object.class), is(true));
|
||||
assertThat(match.matches("this$1", Object.class), is(true));
|
||||
assertThat(match.matches("name", String.class), is(false));
|
||||
assertThat(match.matches("this$0", Object.class)).isTrue();
|
||||
assertThat(match.matches("this$1", Object.class)).isTrue();
|
||||
assertThat(match.matches("name", String.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesFieldByTypeNameOnly() throws Exception {
|
||||
|
||||
PropertyMatch match = new PropertyMatch(null, "java.lang.Object");
|
||||
assertThat(match.matches("this$0", Object.class), is(true));
|
||||
assertThat(match.matches("this$1", Object.class), is(true));
|
||||
assertThat(match.matches("name", String.class), is(false));
|
||||
assertThat(match.matches("this$0", Object.class)).isTrue();
|
||||
assertThat(match.matches("this$1", Object.class)).isTrue();
|
||||
assertThat(match.matches("name", String.class)).isFalse();
|
||||
}
|
||||
|
||||
static class Sample {
|
||||
|
||||
@@ -2,13 +2,14 @@ package org.springframework.data.mapping.context;
|
||||
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.mapping.model.BasicPersistentEntity;
|
||||
import org.springframework.data.mapping.model.SimpleTypeHolder;
|
||||
import org.springframework.data.util.TypeInformation;
|
||||
|
||||
public class SampleMappingContext extends
|
||||
AbstractMappingContext<BasicPersistentEntity<Object, SamplePersistentProperty>, SamplePersistentProperty> {
|
||||
public class SampleMappingContext
|
||||
extends AbstractMappingContext<BasicPersistentEntity<Object, SamplePersistentProperty>, SamplePersistentProperty> {
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -18,8 +19,8 @@ public class SampleMappingContext extends
|
||||
}
|
||||
|
||||
@Override
|
||||
protected SamplePersistentProperty createPersistentProperty(final Field field, final PropertyDescriptor descriptor,
|
||||
final BasicPersistentEntity<Object, SamplePersistentProperty> owner, final SimpleTypeHolder simpleTypeHolder) {
|
||||
protected SamplePersistentProperty createPersistentProperty(Optional<Field> field, PropertyDescriptor descriptor,
|
||||
BasicPersistentEntity<Object, SamplePersistentProperty> owner, SimpleTypeHolder simpleTypeHolder) {
|
||||
|
||||
return new SamplePersistentProperty(field, descriptor, owner, simpleTypeHolder);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ package org.springframework.data.mapping.context;
|
||||
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.mapping.Association;
|
||||
import org.springframework.data.mapping.model.AnnotationBasedPersistentProperty;
|
||||
@@ -25,7 +26,7 @@ import org.springframework.data.mapping.model.SimpleTypeHolder;
|
||||
|
||||
public class SamplePersistentProperty extends AnnotationBasedPersistentProperty<SamplePersistentProperty> {
|
||||
|
||||
public SamplePersistentProperty(Field field, PropertyDescriptor propertyDescriptor,
|
||||
public SamplePersistentProperty(Optional<Field> field, PropertyDescriptor propertyDescriptor,
|
||||
BasicPersistentEntity<?, SamplePersistentProperty> owner, SimpleTypeHolder simpleTypeHolder) {
|
||||
super(field, propertyDescriptor, owner, simpleTypeHolder);
|
||||
}
|
||||
|
||||
118
src/test/java/org/springframework/data/mapping/model/AbstractPersistentPropertyUnitTests.java
Normal file → Executable file
118
src/test/java/org/springframework/data/mapping/model/AbstractPersistentPropertyUnitTests.java
Normal file → Executable file
@@ -15,17 +15,17 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.beans.BeanInfo;
|
||||
import java.beans.IntrospectionException;
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.TreeMap;
|
||||
import java.util.TreeSet;
|
||||
|
||||
@@ -63,7 +63,7 @@ public class AbstractPersistentPropertyUnitTests {
|
||||
|
||||
Field field = ReflectionUtils.findField(TestClassComplex.class, "testClassSet");
|
||||
|
||||
SamplePersistentProperty property = new SamplePersistentProperty(field, null, entity, typeHolder);
|
||||
SamplePersistentProperty property = new SamplePersistentProperty(Optional.of(field), null, entity, typeHolder);
|
||||
property.getComponentType();
|
||||
}
|
||||
|
||||
@@ -72,24 +72,24 @@ public class AbstractPersistentPropertyUnitTests {
|
||||
|
||||
Field field = ReflectionUtils.findField(TestClassComplex.class, "testClassSet");
|
||||
|
||||
SamplePersistentProperty property = new SamplePersistentProperty(field, null, entity, typeHolder);
|
||||
assertThat(property.getPersistentEntityType().iterator().hasNext(), is(false));
|
||||
SamplePersistentProperty property = new SamplePersistentProperty(Optional.of(field), null, entity, typeHolder);
|
||||
assertThat(property.getPersistentEntityType().iterator().hasNext()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-132
|
||||
public void isEntityWorksForUntypedMaps() throws Exception {
|
||||
|
||||
Field field = ReflectionUtils.findField(TestClassComplex.class, "map");
|
||||
SamplePersistentProperty property = new SamplePersistentProperty(field, null, entity, typeHolder);
|
||||
assertThat(property.isEntity(), is(false));
|
||||
SamplePersistentProperty property = new SamplePersistentProperty(Optional.of(field), null, entity, typeHolder);
|
||||
assertThat(property.isEntity()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-132
|
||||
public void isEntityWorksForUntypedCollection() throws Exception {
|
||||
|
||||
Field field = ReflectionUtils.findField(TestClassComplex.class, "collection");
|
||||
SamplePersistentProperty property = new SamplePersistentProperty(field, null, entity, typeHolder);
|
||||
assertThat(property.isEntity(), is(false));
|
||||
SamplePersistentProperty property = new SamplePersistentProperty(Optional.of(field), null, entity, typeHolder);
|
||||
assertThat(property.isEntity()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-121
|
||||
@@ -98,11 +98,12 @@ public class AbstractPersistentPropertyUnitTests {
|
||||
Field first = ReflectionUtils.findField(FirstConcrete.class, "genericField");
|
||||
Field second = ReflectionUtils.findField(SecondConcrete.class, "genericField");
|
||||
|
||||
SamplePersistentProperty firstProperty = new SamplePersistentProperty(first, null, entity, typeHolder);
|
||||
SamplePersistentProperty secondProperty = new SamplePersistentProperty(second, null, entity, typeHolder);
|
||||
SamplePersistentProperty firstProperty = new SamplePersistentProperty(Optional.of(first), null, entity, typeHolder);
|
||||
SamplePersistentProperty secondProperty = new SamplePersistentProperty(Optional.of(second), null, entity,
|
||||
typeHolder);
|
||||
|
||||
assertThat(firstProperty, is(secondProperty));
|
||||
assertThat(firstProperty.hashCode(), is(secondProperty.hashCode()));
|
||||
assertThat(firstProperty).isEqualTo(secondProperty);
|
||||
assertThat(firstProperty.hashCode()).isEqualTo(secondProperty.hashCode());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-180
|
||||
@@ -110,115 +111,116 @@ public class AbstractPersistentPropertyUnitTests {
|
||||
|
||||
Field transientField = ReflectionUtils.findField(TestClassComplex.class, "transientField");
|
||||
|
||||
PersistentProperty<?> property = new SamplePersistentProperty(transientField, null, entity, typeHolder);
|
||||
assertThat(property.isTransient(), is(false));
|
||||
PersistentProperty<?> property = new SamplePersistentProperty(Optional.of(transientField), null, entity,
|
||||
typeHolder);
|
||||
assertThat(property.isTransient()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-206
|
||||
public void findsSimpleGettersAndASetters() {
|
||||
|
||||
Field field = ReflectionUtils.findField(AccessorTestClass.class, "id");
|
||||
PersistentProperty<SamplePersistentProperty> property = new SamplePersistentProperty(field, getPropertyDescriptor(
|
||||
AccessorTestClass.class, "id"), entity, typeHolder);
|
||||
PersistentProperty<SamplePersistentProperty> property = new SamplePersistentProperty(Optional.of(field),
|
||||
getPropertyDescriptor(AccessorTestClass.class, "id"), entity, typeHolder);
|
||||
|
||||
assertThat(property.getGetter(), is(notNullValue()));
|
||||
assertThat(property.getSetter(), is(notNullValue()));
|
||||
assertThat(property.getGetter()).isNotNull();
|
||||
assertThat(property.getSetter()).isNotNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-206
|
||||
public void doesNotUseInvalidGettersAndASetters() {
|
||||
|
||||
Field field = ReflectionUtils.findField(AccessorTestClass.class, "anotherId");
|
||||
PersistentProperty<SamplePersistentProperty> property = new SamplePersistentProperty(field, getPropertyDescriptor(
|
||||
AccessorTestClass.class, "anotherId"), entity, typeHolder);
|
||||
PersistentProperty<SamplePersistentProperty> property = new SamplePersistentProperty(Optional.of(field),
|
||||
getPropertyDescriptor(AccessorTestClass.class, "anotherId"), entity, typeHolder);
|
||||
|
||||
assertThat(property.getGetter(), is(nullValue()));
|
||||
assertThat(property.getSetter(), is(nullValue()));
|
||||
assertThat(property.getGetter()).isNull();
|
||||
assertThat(property.getSetter()).isNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-206
|
||||
public void usesCustomGetter() {
|
||||
|
||||
Field field = ReflectionUtils.findField(AccessorTestClass.class, "yetAnotherId");
|
||||
PersistentProperty<SamplePersistentProperty> property = new SamplePersistentProperty(field, getPropertyDescriptor(
|
||||
AccessorTestClass.class, "yetAnotherId"), entity, typeHolder);
|
||||
PersistentProperty<SamplePersistentProperty> property = new SamplePersistentProperty(Optional.of(field),
|
||||
getPropertyDescriptor(AccessorTestClass.class, "yetAnotherId"), entity, typeHolder);
|
||||
|
||||
assertThat(property.getGetter(), is(notNullValue()));
|
||||
assertThat(property.getSetter(), is(nullValue()));
|
||||
assertThat(property.getGetter()).isNotNull();
|
||||
assertThat(property.getSetter()).isNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-206
|
||||
public void usesCustomSetter() {
|
||||
|
||||
Field field = ReflectionUtils.findField(AccessorTestClass.class, "yetYetAnotherId");
|
||||
PersistentProperty<SamplePersistentProperty> property = new SamplePersistentProperty(field, getPropertyDescriptor(
|
||||
AccessorTestClass.class, "yetYetAnotherId"), entity, typeHolder);
|
||||
PersistentProperty<SamplePersistentProperty> property = new SamplePersistentProperty(Optional.of(field),
|
||||
getPropertyDescriptor(AccessorTestClass.class, "yetYetAnotherId"), entity, typeHolder);
|
||||
|
||||
assertThat(property.getGetter(), is(nullValue()));
|
||||
assertThat(property.getSetter(), is(notNullValue()));
|
||||
assertThat(property.getGetter()).isNull();
|
||||
assertThat(property.getSetter()).isNotNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-206
|
||||
public void returnsNullGetterAndSetterIfNoPropertyDescriptorGiven() {
|
||||
|
||||
Field field = ReflectionUtils.findField(AccessorTestClass.class, "id");
|
||||
PersistentProperty<SamplePersistentProperty> property = new SamplePersistentProperty(field, null, entity,
|
||||
typeHolder);
|
||||
PersistentProperty<SamplePersistentProperty> property = new SamplePersistentProperty(Optional.of(field), null,
|
||||
entity, typeHolder);
|
||||
|
||||
assertThat(property.getGetter(), is(nullValue()));
|
||||
assertThat(property.getSetter(), is(nullValue()));
|
||||
assertThat(property.getGetter()).isNull();
|
||||
assertThat(property.getSetter()).isNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-337
|
||||
public void resolvesActualType() {
|
||||
|
||||
SamplePersistentProperty property = getProperty(Sample.class, "person");
|
||||
assertThat(property.getActualType(), is((Object) Person.class));
|
||||
assertThat(property.getActualType()).isEqualTo(Person.class);
|
||||
|
||||
property = getProperty(Sample.class, "persons");
|
||||
assertThat(property.getActualType(), is((Object) Person.class));
|
||||
assertThat(property.getActualType()).isEqualTo(Person.class);
|
||||
|
||||
property = getProperty(Sample.class, "personArray");
|
||||
assertThat(property.getActualType(), is((Object) Person.class));
|
||||
assertThat(property.getActualType()).isEqualTo(Person.class);
|
||||
|
||||
property = getProperty(Sample.class, "personMap");
|
||||
assertThat(property.getActualType(), is((Object) Person.class));
|
||||
assertThat(property.getActualType()).isEqualTo(Person.class);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-462
|
||||
public void considersCollectionPropertyEntitiesIfComponentTypeIsEntity() {
|
||||
|
||||
SamplePersistentProperty property = getProperty(Sample.class, "persons");
|
||||
assertThat(property.isEntity(), is(true));
|
||||
assertThat(property.isEntity()).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-462
|
||||
public void considersMapPropertyEntitiesIfValueTypeIsEntity() {
|
||||
|
||||
SamplePersistentProperty property = getProperty(Sample.class, "personMap");
|
||||
assertThat(property.isEntity(), is(true));
|
||||
assertThat(property.isEntity()).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-462
|
||||
public void considersArrayPropertyEntitiesIfComponentTypeIsEntity() {
|
||||
|
||||
SamplePersistentProperty property = getProperty(Sample.class, "personArray");
|
||||
assertThat(property.isEntity(), is(true));
|
||||
assertThat(property.isEntity()).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-462
|
||||
public void considersCollectionPropertySimpleIfComponentTypeIsSimple() {
|
||||
|
||||
SamplePersistentProperty property = getProperty(Sample.class, "strings");
|
||||
assertThat(property.isEntity(), is(false));
|
||||
assertThat(property.isEntity()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-562
|
||||
public void doesNotConsiderPropertyWithTreeMapMapValueAnEntity() {
|
||||
|
||||
SamplePersistentProperty property = getProperty(TreeMapWrapper.class, "map");
|
||||
assertThat(property.getPersistentEntityType(), is(emptyIterable()));
|
||||
assertThat(property.isEntity(), is(false));
|
||||
assertThat(property.getPersistentEntityType()).isEmpty();
|
||||
assertThat(property.isEntity()).isFalse();
|
||||
}
|
||||
|
||||
private <T> SamplePersistentProperty getProperty(Class<T> type, String name) {
|
||||
@@ -227,22 +229,16 @@ public class AbstractPersistentPropertyUnitTests {
|
||||
ClassTypeInformation.from(type));
|
||||
|
||||
Field field = ReflectionUtils.findField(type, name);
|
||||
return new SamplePersistentProperty(field, null, entity, typeHolder);
|
||||
return new SamplePersistentProperty(Optional.of(field), null, entity, typeHolder);
|
||||
}
|
||||
|
||||
private static PropertyDescriptor getPropertyDescriptor(Class<?> type, String propertyName) {
|
||||
|
||||
try {
|
||||
|
||||
BeanInfo info = Introspector.getBeanInfo(type);
|
||||
|
||||
for (PropertyDescriptor descriptor : info.getPropertyDescriptors()) {
|
||||
if (descriptor.getName().equals(propertyName)) {
|
||||
return descriptor;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
return Arrays.stream(Introspector.getBeanInfo(type).getPropertyDescriptors())//
|
||||
.filter(it -> it.getName().equals(propertyName))//
|
||||
.findFirst().orElse(null);
|
||||
|
||||
} catch (IntrospectionException e) {
|
||||
return null;
|
||||
@@ -315,7 +311,7 @@ public class AbstractPersistentPropertyUnitTests {
|
||||
|
||||
class SamplePersistentProperty extends AbstractPersistentProperty<SamplePersistentProperty> {
|
||||
|
||||
public SamplePersistentProperty(Field field, PropertyDescriptor propertyDescriptor,
|
||||
public SamplePersistentProperty(Optional<Field> field, PropertyDescriptor propertyDescriptor,
|
||||
PersistentEntity<?, SamplePersistentProperty> owner, SimpleTypeHolder simpleTypeHolder) {
|
||||
super(field, propertyDescriptor, owner, simpleTypeHolder);
|
||||
}
|
||||
@@ -339,8 +335,8 @@ public class AbstractPersistentPropertyUnitTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
public <A extends Annotation> A findAnnotation(Class<A> annotationType) {
|
||||
return null;
|
||||
public <A extends Annotation> Optional<A> findAnnotation(Class<A> annotationType) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -349,8 +345,8 @@ public class AbstractPersistentPropertyUnitTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
public <A extends Annotation> A findPropertyOrOwnerAnnotation(Class<A> annotationType) {
|
||||
return null;
|
||||
public <A extends Annotation> Optional<A> findPropertyOrOwnerAnnotation(Class<A> annotationType) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
87
src/test/java/org/springframework/data/mapping/model/AnnotationBasedPersistentPropertyUnitTests.java
Normal file → Executable file
87
src/test/java/org/springframework/data/mapping/model/AnnotationBasedPersistentPropertyUnitTests.java
Normal file → Executable file
@@ -16,14 +16,14 @@
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static java.lang.annotation.ElementType.*;
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
@@ -83,17 +83,18 @@ public class AnnotationBasedPersistentPropertyUnitTests<P extends AnnotationBase
|
||||
@Test // DATACMNS-282
|
||||
public void populatesAnnotationCacheWithDirectAnnotationsOnCreation() {
|
||||
|
||||
SamplePersistentProperty property = entity.getPersistentProperty("meta");
|
||||
assertThat(entity.getPersistentProperty("meta")).hasValueSatisfying(property -> {
|
||||
|
||||
// Assert direct annotations are cached on construction
|
||||
Map<Class<? extends Annotation>, Annotation> cache = getAnnotationCache(property);
|
||||
assertThat(cache.containsKey(MyAnnotationAsMeta.class), is(true));
|
||||
assertThat(cache.containsKey(MyAnnotation.class), is(false));
|
||||
// Assert direct annotations are cached on construction
|
||||
Map<Class<? extends Annotation>, Annotation> cache = getAnnotationCache(property);
|
||||
assertThat(cache.containsKey(MyAnnotationAsMeta.class)).isTrue();
|
||||
assertThat(cache.containsKey(MyAnnotation.class)).isFalse();
|
||||
|
||||
// Assert meta annotation is found and cached
|
||||
MyAnnotation annotation = property.findAnnotation(MyAnnotation.class);
|
||||
assertThat(annotation, is(notNullValue()));
|
||||
assertThat(cache.containsKey(MyAnnotation.class), is(true));
|
||||
// Assert meta annotation is found and cached
|
||||
assertThat(property.findAnnotation(MyAnnotation.class)).hasValueSatisfying(annotation -> {
|
||||
assertThat(cache.containsKey(MyAnnotation.class)).isTrue();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-282
|
||||
@@ -103,28 +104,28 @@ public class AnnotationBasedPersistentPropertyUnitTests<P extends AnnotationBase
|
||||
context.getPersistentEntity(InvalidSample.class);
|
||||
fail("Expected MappingException!");
|
||||
} catch (MappingException o_O) {
|
||||
assertThat(context.hasPersistentEntityFor(InvalidSample.class), is(false));
|
||||
assertThat(context.hasPersistentEntityFor(InvalidSample.class)).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@Test // DATACMNS-243
|
||||
public void defaultsToFieldAccess() {
|
||||
assertThat(getProperty(FieldAccess.class, "name").usePropertyAccess(), is(false));
|
||||
assertThat(getProperty(FieldAccess.class, "name").usePropertyAccess()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-243
|
||||
public void usesAccessTypeDeclaredOnTypeAsDefault() {
|
||||
assertThat(getProperty(PropertyAccess.class, "firstname").usePropertyAccess(), is(true));
|
||||
assertThat(getProperty(PropertyAccess.class, "firstname").usePropertyAccess()).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-243
|
||||
public void propertyAnnotationOverridesTypeConfiguration() {
|
||||
assertThat(getProperty(PropertyAccess.class, "lastname").usePropertyAccess(), is(false));
|
||||
assertThat(getProperty(PropertyAccess.class, "lastname").usePropertyAccess()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-243
|
||||
public void fieldAnnotationOverridesTypeConfiguration() {
|
||||
assertThat(getProperty(PropertyAccess.class, "emailAddress").usePropertyAccess(), is(false));
|
||||
assertThat(getProperty(PropertyAccess.class, "emailAddress").usePropertyAccess()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-243
|
||||
@@ -134,22 +135,22 @@ public class AnnotationBasedPersistentPropertyUnitTests<P extends AnnotationBase
|
||||
|
||||
@Test // DATACMNS-534
|
||||
public void treatsNoAnnotationCorrectly() {
|
||||
assertThat(getProperty(ClassWithReadOnlyProperties.class, "noAnnotations").isWritable(), is(true));
|
||||
assertThat(getProperty(ClassWithReadOnlyProperties.class, "noAnnotations").isWritable()).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-534
|
||||
public void treatsTransientAsNotExisting() {
|
||||
assertThat(getProperty(ClassWithReadOnlyProperties.class, "transientProperty"), nullValue());
|
||||
assertThat(getProperty(ClassWithReadOnlyProperties.class, "transientProperty")).isNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-534
|
||||
public void treatsReadOnlyAsNonWritable() {
|
||||
assertThat(getProperty(ClassWithReadOnlyProperties.class, "readOnlyProperty").isWritable(), is(false));
|
||||
assertThat(getProperty(ClassWithReadOnlyProperties.class, "readOnlyProperty").isWritable()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-534
|
||||
public void considersPropertyWithReadOnlyMetaAnnotationReadOnly() {
|
||||
assertThat(getProperty(ClassWithReadOnlyProperties.class, "customReadOnlyProperty").isWritable(), is(false));
|
||||
assertThat(getProperty(ClassWithReadOnlyProperties.class, "customReadOnlyProperty").isWritable()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-556
|
||||
@@ -163,37 +164,39 @@ public class AnnotationBasedPersistentPropertyUnitTests<P extends AnnotationBase
|
||||
|
||||
SamplePersistentProperty property = getProperty(Sample.class, "getterWithoutField");
|
||||
|
||||
assertThat(property.findAnnotation(MyAnnotation.class), is(nullValue()));
|
||||
assertThat(property.findAnnotation(MyAnnotation.class)).isNotPresent();
|
||||
|
||||
Map<Class<?>, ?> field = (Map<Class<?>, ?>) ReflectionTestUtils.getField(property, "annotationCache");
|
||||
|
||||
assertThat(field.containsKey(MyAnnotation.class), is(true));
|
||||
assertThat(field.get(MyAnnotation.class), is(nullValue()));
|
||||
assertThat(field.containsKey(MyAnnotation.class)).isTrue();
|
||||
assertThat(field.get(MyAnnotation.class)).isEqualTo(Optional.empty());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-825
|
||||
public void composedAnnotationWithAliasForGetCachedCorrectly() {
|
||||
|
||||
SamplePersistentProperty property = entity.getPersistentProperty("metaAliased");
|
||||
assertThat(entity.getPersistentProperty("metaAliased")).hasValueSatisfying(property -> {
|
||||
|
||||
// Assert direct annotations are cached on construction
|
||||
Map<Class<? extends Annotation>, Annotation> cache = getAnnotationCache(property);
|
||||
assertThat(cache.containsKey(MyComposedAnnotationUsingAliasFor.class), is(true));
|
||||
assertThat(cache.containsKey(MyAnnotation.class), is(false));
|
||||
// Assert direct annotations are cached on construction
|
||||
Map<Class<? extends Annotation>, Annotation> cache = getAnnotationCache(property);
|
||||
assertThat(cache.containsKey(MyComposedAnnotationUsingAliasFor.class)).isTrue();
|
||||
assertThat(cache.containsKey(MyAnnotation.class)).isFalse();
|
||||
|
||||
// Assert meta annotation is found and cached
|
||||
MyAnnotation annotation = property.findAnnotation(MyAnnotation.class);
|
||||
assertThat(annotation, is(notNullValue()));
|
||||
assertThat(cache.containsKey(MyAnnotation.class), is(true));
|
||||
// Assert meta annotation is found and cached
|
||||
assertThat(property.findAnnotation(MyAnnotation.class)).hasValueSatisfying(it -> {
|
||||
assertThat(cache.containsKey(MyAnnotation.class)).isTrue();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-825
|
||||
public void composedAnnotationWithAliasShouldHaveSynthesizedAttributeValues() {
|
||||
|
||||
SamplePersistentProperty property = entity.getPersistentProperty("metaAliased");
|
||||
|
||||
MyAnnotation annotation = property.findAnnotation(MyAnnotation.class);
|
||||
assertThat(AnnotationUtils.getValue(annotation), is((Object) "spring"));
|
||||
assertThat(entity.getPersistentProperty("metaAliased")).hasValueSatisfying(property -> {
|
||||
assertThat(property.findAnnotation(MyAnnotation.class)).hasValueSatisfying(annotation -> {
|
||||
assertThat(AnnotationUtils.getValue(annotation)).isEqualTo("spring");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -202,15 +205,17 @@ public class AnnotationBasedPersistentPropertyUnitTests<P extends AnnotationBase
|
||||
}
|
||||
|
||||
private <A extends Annotation> A assertAnnotationPresent(Class<A> annotationType,
|
||||
AnnotationBasedPersistentProperty<?> property) {
|
||||
Optional<? extends AnnotationBasedPersistentProperty<?>> property) {
|
||||
|
||||
A annotation = property.findAnnotation(annotationType);
|
||||
assertThat(annotation, is(notNullValue()));
|
||||
return annotation;
|
||||
Optional<A> annotation = property.flatMap(it -> it.findAnnotation(annotationType));
|
||||
|
||||
assertThat(annotation).isPresent();
|
||||
|
||||
return annotation.get();
|
||||
}
|
||||
|
||||
private SamplePersistentProperty getProperty(Class<?> type, String name) {
|
||||
return context.getPersistentEntity(type).getPersistentProperty(name);
|
||||
return context.getPersistentEntity(type).getPersistentProperty(name).orElse(null);
|
||||
}
|
||||
|
||||
static class Sample {
|
||||
|
||||
52
src/test/java/org/springframework/data/mapping/model/BasicPersistentEntityUnitTests.java
Normal file → Executable file
52
src/test/java/org/springframework/data/mapping/model/BasicPersistentEntityUnitTests.java
Normal file → Executable file
@@ -15,8 +15,9 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
import static org.junit.Assume.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -25,6 +26,7 @@ import java.lang.annotation.RetentionPolicy;
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.junit.Assert;
|
||||
@@ -84,14 +86,14 @@ public class BasicPersistentEntityUnitTests<T extends PersistentProperty<T>> {
|
||||
public void returnsNullForTypeAliasIfNoneConfigured() {
|
||||
|
||||
PersistentEntity<Entity, T> entity = createEntity(Entity.class);
|
||||
assertThat(entity.getTypeAlias(), is(nullValue()));
|
||||
assertThat(entity.getTypeAlias()).isNotPresent();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void returnsTypeAliasIfAnnotated() {
|
||||
|
||||
PersistentEntity<AliasedEntity, T> entity = createEntity(AliasedEntity.class);
|
||||
assertThat(entity.getTypeAlias(), is((Object) "foo"));
|
||||
assertThat(entity.getTypeAlias()).isEqualTo("foo");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-50
|
||||
@@ -120,22 +122,22 @@ public class BasicPersistentEntityUnitTests<T extends PersistentProperty<T>> {
|
||||
|
||||
List<T> properties = (List<T>) ReflectionTestUtils.getField(entity, "properties");
|
||||
|
||||
assertThat(properties.size(), is(3));
|
||||
assertThat(properties).hasSize(3);
|
||||
Iterator<T> iterator = properties.iterator();
|
||||
assertThat(iterator.next(), is(entity.getPersistentProperty("firstName")));
|
||||
assertThat(iterator.next(), is(entity.getPersistentProperty("lastName")));
|
||||
assertThat(iterator.next(), is(entity.getPersistentProperty("ssn")));
|
||||
assertThat(iterator.next()).isEqualTo(entity.getPersistentProperty("firstName"));
|
||||
assertThat(iterator.next()).isEqualTo(entity.getPersistentProperty("lastName"));
|
||||
assertThat(iterator.next()).isEqualTo(entity.getPersistentProperty("ssn"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-186
|
||||
public void addingAndIdPropertySetsIdPropertyInternally() {
|
||||
|
||||
MutablePersistentEntity<Person, T> entity = createEntity(Person.class);
|
||||
assertThat(entity.getIdProperty(), is(nullValue()));
|
||||
assertThat(entity.getIdProperty()).isNull();
|
||||
|
||||
when(property.isIdProperty()).thenReturn(true);
|
||||
entity.addPersistentProperty(property);
|
||||
assertThat(entity.getIdProperty(), is(property));
|
||||
assertThat(entity.getIdProperty()).isEqualTo(property);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-186
|
||||
@@ -157,15 +159,19 @@ public class BasicPersistentEntityUnitTests<T extends PersistentProperty<T>> {
|
||||
SampleMappingContext context = new SampleMappingContext();
|
||||
PersistentEntity<Object, SamplePersistentProperty> entity = context.getPersistentEntity(Entity.class);
|
||||
|
||||
PersistentProperty<?> property = entity.getPersistentProperty(LastModifiedBy.class);
|
||||
assertThat(property, is(notNullValue()));
|
||||
assertThat(property.getName(), is("field"));
|
||||
Optional<SamplePersistentProperty> property = entity.getPersistentProperty(LastModifiedBy.class);
|
||||
|
||||
assertThat(property).hasValueSatisfying(it -> {
|
||||
assertThat(it.getName()).isEqualTo("field");
|
||||
});
|
||||
|
||||
property = entity.getPersistentProperty(CreatedBy.class);
|
||||
assertThat(property, is(notNullValue()));
|
||||
assertThat(property.getName(), is("property"));
|
||||
|
||||
assertThat(entity.getPersistentProperty(CreatedDate.class), is(nullValue()));
|
||||
assertThat(property).hasValueSatisfying(it -> {
|
||||
assertThat(it.getName()).isEqualTo("property");
|
||||
});
|
||||
|
||||
assertThat(entity.getPersistentProperty(CreatedDate.class)).isNotPresent();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-596
|
||||
@@ -179,8 +185,8 @@ public class BasicPersistentEntityUnitTests<T extends PersistentProperty<T>> {
|
||||
Entity value = new Entity();
|
||||
PersistentPropertyAccessor accessor = entity.getPropertyAccessor(value);
|
||||
|
||||
assertThat(accessor, is(instanceOf(BeanWrapper.class)));
|
||||
assertThat(accessor.getBean(), is((Object) value));
|
||||
assertThat(accessor).isEqualTo(instanceOf(BeanWrapper.class));
|
||||
assertThat(accessor.getBean()).isEqualTo(value);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-809
|
||||
@@ -194,9 +200,9 @@ public class BasicPersistentEntityUnitTests<T extends PersistentProperty<T>> {
|
||||
Entity value = new Entity();
|
||||
PersistentPropertyAccessor accessor = entity.getPropertyAccessor(value);
|
||||
|
||||
assertThat(accessor, is(not(instanceOf(BeanWrapper.class))));
|
||||
assertThat(accessor.getClass().getName(), containsString("_Accessor_"));
|
||||
assertThat(accessor.getBean(), is((Object) value));
|
||||
assertThat(accessor).isNotEqualTo(instanceOf(BeanWrapper.class));
|
||||
assertThat(accessor.getClass().getName()).contains("_Accessor_");
|
||||
assertThat(accessor.getBean()).isEqualTo(value);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class) // DATACMNS-596
|
||||
@@ -223,7 +229,7 @@ public class BasicPersistentEntityUnitTests<T extends PersistentProperty<T>> {
|
||||
SampleMappingContext context = new SampleMappingContext();
|
||||
PersistentEntity<Object, SamplePersistentProperty> entity = context.getPersistentEntity(Entity.class);
|
||||
|
||||
assertThat(entity.getPropertyAccessor(new Subtype()), is(notNullValue()));
|
||||
assertThat(entity.getPropertyAccessor(new Subtype())).isNotNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-825
|
||||
@@ -231,7 +237,7 @@ public class BasicPersistentEntityUnitTests<T extends PersistentProperty<T>> {
|
||||
|
||||
PersistentEntity<AliasEntityUsingComposedAnnotation, T> entity = createEntity(
|
||||
AliasEntityUsingComposedAnnotation.class);
|
||||
assertThat(entity.getTypeAlias(), is((Object) "bar"));
|
||||
assertThat(entity.getTypeAlias()).isEqualTo("bar");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-866
|
||||
@@ -265,7 +271,7 @@ public class BasicPersistentEntityUnitTests<T extends PersistentProperty<T>> {
|
||||
}
|
||||
|
||||
private <S> BasicPersistentEntity<S, T> createEntity(Class<S> type, Comparator<T> comparator) {
|
||||
return new BasicPersistentEntity<S, T>(ClassTypeInformation.from(type), comparator);
|
||||
return new BasicPersistentEntity<S, T>(ClassTypeInformation.from(type), Optional.ofNullable(comparator));
|
||||
}
|
||||
|
||||
@TypeAlias("foo")
|
||||
|
||||
5
src/test/java/org/springframework/data/mapping/model/CamelCaseAbbreviatingFieldNamingStrategyUnitTests.java
Normal file → Executable file
5
src/test/java/org/springframework/data/mapping/model/CamelCaseAbbreviatingFieldNamingStrategyUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.junit.Test;
|
||||
@@ -48,6 +47,6 @@ public class CamelCaseAbbreviatingFieldNamingStrategyUnitTests {
|
||||
private void assertFieldNameForPropertyName(String propertyName, String fieldName) {
|
||||
|
||||
when(property.getName()).thenReturn(propertyName);
|
||||
assertThat(strategy.getFieldName(property), is(fieldName));
|
||||
assertThat(strategy.getFieldName(property)).isEqualTo(fieldName);
|
||||
}
|
||||
}
|
||||
|
||||
29
src/test/java/org/springframework/data/mapping/model/ClassGeneratingPropertyAccessorFactoryDatatypeTests.java
Normal file → Executable file
29
src/test/java/org/springframework/data/mapping/model/ClassGeneratingPropertyAccessorFactoryDatatypeTests.java
Normal file → Executable file
@@ -15,10 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.instanceOf;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@@ -26,6 +23,7 @@ import java.lang.reflect.Constructor;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
@@ -53,21 +51,20 @@ public class ClassGeneratingPropertyAccessorFactoryDatatypeTests {
|
||||
|
||||
private final Object bean;
|
||||
private final String propertyName;
|
||||
private final Object value;
|
||||
private final Optional<Object> value;
|
||||
|
||||
public ClassGeneratingPropertyAccessorFactoryDatatypeTests(Object bean, String propertyName, Object value,
|
||||
String displayName) {
|
||||
|
||||
this.bean = bean;
|
||||
this.propertyName = propertyName;
|
||||
this.value = value;
|
||||
this.value = Optional.of(value);
|
||||
}
|
||||
|
||||
@Parameters(name = "{3}")
|
||||
@SuppressWarnings("unchecked")
|
||||
public static List<Object[]> parameters() throws Exception {
|
||||
|
||||
List<Object[]> parameters = new ArrayList<Object[]>();
|
||||
List<Object[]> parameters = new ArrayList<>();
|
||||
List<Class<?>> types = Arrays.asList(FieldAccess.class, PropertyAccess.class, PrivateFinalFieldAccess.class, PrivateFinalPropertyAccess.class);
|
||||
|
||||
parameters.addAll(parameters(types, "primitiveInteger", Integer.valueOf(1)));
|
||||
@@ -126,11 +123,13 @@ public class ClassGeneratingPropertyAccessorFactoryDatatypeTests {
|
||||
@Test // DATACMNS-809
|
||||
public void shouldSetAndGetProperty() throws Exception {
|
||||
|
||||
PersistentProperty<?> property = getProperty(bean, propertyName);
|
||||
PersistentPropertyAccessor persistentPropertyAccessor = getPersistentPropertyAccessor(bean);
|
||||
assertThat(getProperty(bean, propertyName)).hasValueSatisfying(property -> {
|
||||
|
||||
persistentPropertyAccessor.setProperty(property, value);
|
||||
assertThat(persistentPropertyAccessor.getProperty(property), is(equalTo((Object) value)));
|
||||
PersistentPropertyAccessor persistentPropertyAccessor = getPersistentPropertyAccessor(bean);
|
||||
|
||||
persistentPropertyAccessor.setProperty(property, value);
|
||||
assertThat(persistentPropertyAccessor.getProperty(property)).isEqualTo(value);
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-809
|
||||
@@ -139,15 +138,15 @@ public class ClassGeneratingPropertyAccessorFactoryDatatypeTests {
|
||||
BasicPersistentEntity<Object, SamplePersistentProperty> persistentEntity = mappingContext
|
||||
.getPersistentEntity(bean.getClass());
|
||||
|
||||
assertThat(ReflectionTestUtils.getField(persistentEntity, "propertyAccessorFactory"),
|
||||
is(instanceOf(ClassGeneratingPropertyAccessorFactory.class)));
|
||||
assertThat(ReflectionTestUtils.getField(persistentEntity, "propertyAccessorFactory"))
|
||||
.isInstanceOf(ClassGeneratingPropertyAccessorFactory.class);
|
||||
}
|
||||
|
||||
private PersistentPropertyAccessor getPersistentPropertyAccessor(Object bean) {
|
||||
return factory.getPropertyAccessor(mappingContext.getPersistentEntity(bean.getClass()), bean);
|
||||
}
|
||||
|
||||
private PersistentProperty<?> getProperty(Object bean, String name) {
|
||||
private Optional<? extends PersistentProperty<?>> getProperty(Object bean, String name) {
|
||||
|
||||
BasicPersistentEntity<Object, SamplePersistentProperty> persistentEntity = mappingContext
|
||||
.getPersistentEntity(bean.getClass());
|
||||
|
||||
7
src/test/java/org/springframework/data/mapping/model/ClassGeneratingPropertyAccessorFactoryEntityTypeTests.java
Normal file → Executable file
7
src/test/java/org/springframework/data/mapping/model/ClassGeneratingPropertyAccessorFactoryEntityTypeTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
@@ -43,7 +42,7 @@ public class ClassGeneratingPropertyAccessorFactoryEntityTypeTests {
|
||||
|
||||
Algorithm quickSort = new QuickSort();
|
||||
|
||||
assertThat(getEntityInformation(Algorithm.class).getId(quickSort), is((Object) quickSort.getName()));
|
||||
assertThat(getEntityInformation(Algorithm.class).getId(quickSort)).isEqualTo(quickSort.getName());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-853
|
||||
@@ -51,7 +50,7 @@ public class ClassGeneratingPropertyAccessorFactoryEntityTypeTests {
|
||||
|
||||
Person jonDoe = new Person("JonDoe");
|
||||
|
||||
assertThat(getEntityInformation(Person.class).getId(jonDoe), is((Object) jonDoe.name));
|
||||
assertThat(getEntityInformation(Person.class).getId(jonDoe)).isEqualTo(jonDoe.name);
|
||||
}
|
||||
|
||||
private EntityInformation<Object, ?> getEntityInformation(Class<?> type) {
|
||||
|
||||
41
src/test/java/org/springframework/data/mapping/model/ClassGeneratingPropertyAccessorFactoryTests.java
Normal file → Executable file
41
src/test/java/org/springframework/data/mapping/model/ClassGeneratingPropertyAccessorFactoryTests.java
Normal file → Executable file
@@ -16,15 +16,13 @@
|
||||
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.instanceOf;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
@@ -98,11 +96,13 @@ public class ClassGeneratingPropertyAccessorFactoryTests {
|
||||
@Test // DATACMNS-809
|
||||
public void shouldSetAndGetProperty() throws Exception {
|
||||
|
||||
PersistentProperty<?> property = getProperty(bean, propertyName);
|
||||
PersistentPropertyAccessor persistentPropertyAccessor = getPersistentPropertyAccessor(bean);
|
||||
assertThat(getProperty(bean, propertyName)).hasValueSatisfying(property -> {
|
||||
|
||||
persistentPropertyAccessor.setProperty(property, "value");
|
||||
assertThat(persistentPropertyAccessor.getProperty(property), is(equalTo((Object) "value")));
|
||||
PersistentPropertyAccessor persistentPropertyAccessor = getPersistentPropertyAccessor(bean);
|
||||
|
||||
persistentPropertyAccessor.setProperty(property, Optional.of("value"));
|
||||
assertThat(persistentPropertyAccessor.getProperty(property)).isEqualTo("value");
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-809
|
||||
@@ -112,9 +112,9 @@ public class ClassGeneratingPropertyAccessorFactoryTests {
|
||||
PersistentPropertyAccessor persistentPropertyAccessor = getPersistentPropertyAccessor(bean);
|
||||
|
||||
Constructor<?>[] declaredConstructors = persistentPropertyAccessor.getClass().getDeclaredConstructors();
|
||||
assertThat(declaredConstructors.length, is(1));
|
||||
assertThat(declaredConstructors[0].getParameterTypes().length, is(1));
|
||||
assertThat(declaredConstructors[0].getParameterTypes()[0], is(equalTo((Class) expectedConstructorType)));
|
||||
assertThat(declaredConstructors.length).isEqualTo(1);
|
||||
assertThat(declaredConstructors[0].getParameterTypes().length).isEqualTo(1);
|
||||
assertThat(declaredConstructors[0].getParameterTypes()[0]).isEqualTo(expectedConstructorType);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class) // DATACMNS-809
|
||||
@@ -125,19 +125,20 @@ public class ClassGeneratingPropertyAccessorFactoryTests {
|
||||
@Test(expected = UnsupportedOperationException.class) // DATACMNS-809
|
||||
public void getPropertyShouldFailOnUnhandledProperty() {
|
||||
|
||||
PersistentProperty<?> property = getProperty(new Dummy(), "dummy");
|
||||
PersistentPropertyAccessor persistentPropertyAccessor = getPersistentPropertyAccessor(bean);
|
||||
assertThat(getProperty(new Dummy(), "dummy")).hasValueSatisfying(property -> {
|
||||
|
||||
persistentPropertyAccessor.getProperty(property);
|
||||
assertThatExceptionOfType(UnsupportedOperationException.class)//
|
||||
.isThrownBy(() -> getPersistentPropertyAccessor(bean).getProperty(property));
|
||||
});
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class) // DATACMNS-809
|
||||
public void setPropertyShouldFailOnUnhandledProperty() {
|
||||
|
||||
PersistentProperty<?> property = getProperty(new Dummy(), "dummy");
|
||||
PersistentPropertyAccessor persistentPropertyAccessor = getPersistentPropertyAccessor(bean);
|
||||
assertThat(getProperty(new Dummy(), "dummy")).hasValueSatisfying(property -> {
|
||||
getPersistentPropertyAccessor(bean).setProperty(property, Optional.empty());
|
||||
});
|
||||
|
||||
persistentPropertyAccessor.setProperty(property, null);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-809
|
||||
@@ -146,15 +147,15 @@ public class ClassGeneratingPropertyAccessorFactoryTests {
|
||||
BasicPersistentEntity<Object, SamplePersistentProperty> persistentEntity = mappingContext
|
||||
.getPersistentEntity(bean.getClass());
|
||||
|
||||
assertThat(ReflectionTestUtils.getField(persistentEntity, "propertyAccessorFactory"),
|
||||
is(instanceOf(ClassGeneratingPropertyAccessorFactory.class)));
|
||||
assertThat(ReflectionTestUtils.getField(persistentEntity, "propertyAccessorFactory"))
|
||||
.isInstanceOf(ClassGeneratingPropertyAccessorFactory.class);
|
||||
}
|
||||
|
||||
private PersistentPropertyAccessor getPersistentPropertyAccessor(Object bean) {
|
||||
return factory.getPropertyAccessor(mappingContext.getPersistentEntity(bean.getClass()), bean);
|
||||
}
|
||||
|
||||
private PersistentProperty<?> getProperty(Object bean, String name) {
|
||||
private Optional<? extends PersistentProperty<?>> getProperty(Object bean, String name) {
|
||||
|
||||
BasicPersistentEntity<Object, SamplePersistentProperty> persistentEntity = mappingContext
|
||||
.getPersistentEntity(bean.getClass());
|
||||
|
||||
45
src/test/java/org/springframework/data/mapping/model/ConvertingPropertyAccessorUnitTests.java
Normal file → Executable file
45
src/test/java/org/springframework/data/mapping/model/ConvertingPropertyAccessorUnitTests.java
Normal file → Executable file
@@ -15,10 +15,11 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.core.convert.ConversionService;
|
||||
import org.springframework.data.mapping.PersistentPropertyAccessor;
|
||||
@@ -49,7 +50,7 @@ public class ConvertingPropertyAccessorUnitTests {
|
||||
public void returnsBeanFromDelegate() {
|
||||
|
||||
Object entity = new Entity();
|
||||
assertThat(getAccessor(entity, CONVERSION_SERVICE).getBean(), is(entity));
|
||||
assertThat(getAccessor(entity, CONVERSION_SERVICE).getBean()).isEqualTo(entity);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-596
|
||||
@@ -58,19 +59,20 @@ public class ConvertingPropertyAccessorUnitTests {
|
||||
Entity entity = new Entity();
|
||||
entity.id = 1L;
|
||||
|
||||
ConvertingPropertyAccessor accessor = getAccessor(entity, CONVERSION_SERVICE);
|
||||
|
||||
assertThat(accessor.getProperty(getIdProperty(), String.class), is("1"));
|
||||
assertThat(getIdProperty()).hasValueSatisfying(it -> {
|
||||
assertThat(getAccessor(entity, CONVERSION_SERVICE).getProperty(it, String.class)).hasValue("1");
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-596
|
||||
public void doesNotInvokeConversionForNullValues() {
|
||||
|
||||
ConversionService conversionService = mock(ConversionService.class);
|
||||
ConvertingPropertyAccessor accessor = getAccessor(new Entity(), conversionService);
|
||||
|
||||
assertThat(accessor.getProperty(getIdProperty(), Number.class), is(nullValue()));
|
||||
verify(conversionService, times(0)).convert(1L, Number.class);
|
||||
assertThat(getIdProperty()).hasValueSatisfying(it -> {
|
||||
assertThat(getAccessor(new Entity(), conversionService).getProperty(it, Number.class)).isNotPresent();
|
||||
verify(conversionService, times(0)).convert(1L, Number.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-596
|
||||
@@ -80,30 +82,31 @@ public class ConvertingPropertyAccessorUnitTests {
|
||||
entity.id = 1L;
|
||||
|
||||
ConversionService conversionService = mock(ConversionService.class);
|
||||
ConvertingPropertyAccessor accessor = getAccessor(entity, conversionService);
|
||||
|
||||
assertThat(accessor.getProperty(getIdProperty(), Number.class), is((Number) 1L));
|
||||
verify(conversionService, times(0)).convert(1L, Number.class);
|
||||
assertThat(getIdProperty()).hasValueSatisfying(it -> {
|
||||
assertThat(getAccessor(entity, conversionService).getProperty(it, Number.class)).hasValue(1L);
|
||||
verify(conversionService, times(0)).convert(1L, Number.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-596
|
||||
public void convertsValueOnSetIfTypesDontMatch() {
|
||||
|
||||
Entity entity = new Entity();
|
||||
ConvertingPropertyAccessor accessor = getAccessor(entity, CONVERSION_SERVICE);
|
||||
|
||||
accessor.setProperty(getIdProperty(), "1");
|
||||
|
||||
assertThat(entity.id, is(1L));
|
||||
assertThat(getIdProperty()).hasValueSatisfying(property -> {
|
||||
getAccessor(entity, CONVERSION_SERVICE).setProperty(property, Optional.of("1"));
|
||||
assertThat(entity.id).isEqualTo(1L);
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-596
|
||||
public void doesNotInvokeConversionIfTypeAlreadyMatchesOnSet() {
|
||||
|
||||
ConvertingPropertyAccessor accessor = getAccessor(new Entity(), mock(ConversionService.class));
|
||||
|
||||
accessor.setProperty(getIdProperty(), 1L);
|
||||
verify(mock(ConversionService.class), times(0)).convert(1L, Long.class);
|
||||
assertThat(getIdProperty()).hasValueSatisfying(it -> {
|
||||
getAccessor(new Entity(), mock(ConversionService.class)).setProperty(it, Optional.of(1L));
|
||||
verify(mock(ConversionService.class), times(0)).convert(1L, Long.class);
|
||||
});
|
||||
}
|
||||
|
||||
private static ConvertingPropertyAccessor getAccessor(Object entity, ConversionService conversionService) {
|
||||
@@ -112,7 +115,7 @@ public class ConvertingPropertyAccessorUnitTests {
|
||||
return new ConvertingPropertyAccessor(wrapper, conversionService);
|
||||
}
|
||||
|
||||
private static SamplePersistentProperty getIdProperty() {
|
||||
private static Optional<SamplePersistentProperty> getIdProperty() {
|
||||
|
||||
SampleMappingContext mappingContext = new SampleMappingContext();
|
||||
BasicPersistentEntity<Object, SamplePersistentProperty> entity = mappingContext.getPersistentEntity(Entity.class);
|
||||
|
||||
5
src/test/java/org/springframework/data/mapping/model/IdPropertyIdentifierAccessorUnitTests.java
Normal file → Executable file
5
src/test/java/org/springframework/data/mapping/model/IdPropertyIdentifierAccessorUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.annotation.Id;
|
||||
@@ -51,7 +50,7 @@ public class IdPropertyIdentifierAccessorUnitTests {
|
||||
IdentifierAccessor accessor = new IdPropertyIdentifierAccessor(
|
||||
mappingContext.getPersistentEntity(SampleWithId.class), sample);
|
||||
|
||||
assertThat(accessor.getIdentifier(), is((Object) sample.id));
|
||||
assertThat(accessor.getIdentifier()).isEqualTo(sample.id);
|
||||
}
|
||||
|
||||
static class Sample {}
|
||||
|
||||
60
src/test/java/org/springframework/data/mapping/model/PersistentEntityParameterValueProviderUnitTests.java
Normal file → Executable file
60
src/test/java/org/springframework/data/mapping/model/PersistentEntityParameterValueProviderUnitTests.java
Normal file → Executable file
@@ -15,20 +15,19 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.data.mapping.PersistentEntity;
|
||||
import org.springframework.data.mapping.PersistentProperty;
|
||||
import org.springframework.data.mapping.PreferredConstructor;
|
||||
import org.springframework.data.mapping.PreferredConstructor.Parameter;
|
||||
import org.springframework.data.mapping.model.PersistentEntityParameterValueProviderUnitTests.Outer.Inner;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
@@ -41,13 +40,8 @@ import org.springframework.data.util.ClassTypeInformation;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class PersistentEntityParameterValueProviderUnitTests<P extends PersistentProperty<P>> {
|
||||
|
||||
@Rule
|
||||
public ExpectedException exception = ExpectedException.none();
|
||||
|
||||
@Mock
|
||||
PropertyValueProvider<P> propertyValueProvider;
|
||||
@Mock
|
||||
P property;
|
||||
@Mock PropertyValueProvider<P> propertyValueProvider;
|
||||
@Mock P property;
|
||||
|
||||
@Test // DATACMNS-134
|
||||
public void usesParentObjectAsImplicitFirstConstructorArgument() {
|
||||
@@ -55,35 +49,41 @@ public class PersistentEntityParameterValueProviderUnitTests<P extends Persisten
|
||||
Object outer = new Outer();
|
||||
|
||||
PersistentEntity<Inner, P> entity = new BasicPersistentEntity<Inner, P>(ClassTypeInformation.from(Inner.class)) {
|
||||
|
||||
@Override
|
||||
public P getPersistentProperty(String name) {
|
||||
return property;
|
||||
public Optional<P> getPersistentProperty(String name) {
|
||||
return Optional.ofNullable(property);
|
||||
}
|
||||
};
|
||||
PreferredConstructor<Inner, P> constructor = entity.getPersistenceConstructor();
|
||||
Iterator<Parameter<Object, P>> iterator = constructor.getParameters().iterator();
|
||||
|
||||
ParameterValueProvider<P> provider = new PersistentEntityParameterValueProvider<P>(entity, propertyValueProvider,
|
||||
outer);
|
||||
assertThat(provider.getParameterValue(iterator.next()), is(outer));
|
||||
assertThat(provider.getParameterValue(iterator.next()), is(nullValue()));
|
||||
assertThat(iterator.hasNext(), is(false));
|
||||
doReturn(Optional.empty()).when(propertyValueProvider).getPropertyValue(any());
|
||||
|
||||
assertThat(entity.getPersistenceConstructor()).hasValueSatisfying(constructor -> {
|
||||
|
||||
Iterator<Parameter<Object, P>> iterator = constructor.getParameters().iterator();
|
||||
ParameterValueProvider<P> provider = new PersistentEntityParameterValueProvider<>(entity, propertyValueProvider,
|
||||
Optional.of(outer));
|
||||
|
||||
assertThat(provider.getParameterValue(iterator.next())).hasValue(outer);
|
||||
assertThat(provider.getParameterValue(iterator.next())).isNotPresent();
|
||||
assertThat(iterator.hasNext()).isFalse();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsPropertyIfNameDoesNotMatch() {
|
||||
|
||||
PersistentEntity<Entity, P> entity = new BasicPersistentEntity<Entity, P>(ClassTypeInformation.from(Entity.class));
|
||||
ParameterValueProvider<P> provider = new PersistentEntityParameterValueProvider<P>(entity, propertyValueProvider,
|
||||
property);
|
||||
PersistentEntity<Entity, P> entity = new BasicPersistentEntity<>(ClassTypeInformation.from(Entity.class));
|
||||
ParameterValueProvider<P> provider = new PersistentEntityParameterValueProvider<>(entity, propertyValueProvider,
|
||||
Optional.of(property));
|
||||
|
||||
PreferredConstructor<Entity, P> constructor = entity.getPersistenceConstructor();
|
||||
assertThat(entity.getPersistenceConstructor()).hasValueSatisfying(constructor -> {
|
||||
|
||||
exception.expect(MappingException.class);
|
||||
exception.expectMessage("bar");
|
||||
exception.expectMessage(Entity.class.getName());
|
||||
|
||||
provider.getParameterValue(constructor.getParameters().iterator().next());
|
||||
assertThatExceptionOfType(MappingException.class)//
|
||||
.isThrownBy(() -> provider.getParameterValue(constructor.getParameters().iterator().next()))//
|
||||
.withMessageContaining("bar")//
|
||||
.withMessageContaining(Entity.class.getName());
|
||||
});
|
||||
}
|
||||
|
||||
static class Outer {
|
||||
|
||||
5
src/test/java/org/springframework/data/mapping/model/SnakeCaseFieldNamingStrategyUnitTests.java
Normal file → Executable file
5
src/test/java/org/springframework/data/mapping/model/SnakeCaseFieldNamingStrategyUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.junit.Test;
|
||||
@@ -51,6 +50,6 @@ public class SnakeCaseFieldNamingStrategyUnitTests {
|
||||
private void assertFieldNameForPropertyName(String propertyName, String fieldName) {
|
||||
|
||||
when(property.getName()).thenReturn(propertyName);
|
||||
assertThat(strategy.getFieldName(property), is(fieldName));
|
||||
assertThat(strategy.getFieldName(property)).isEqualTo(fieldName);
|
||||
}
|
||||
}
|
||||
|
||||
19
src/test/java/org/springframework/data/mapping/model/SpelExpressionParameterProviderUnitTests.java
Normal file → Executable file
19
src/test/java/org/springframework/data/mapping/model/SpelExpressionParameterProviderUnitTests.java
Normal file → Executable file
@@ -15,10 +15,11 @@
|
||||
*/
|
||||
package org.springframework.data.mapping.model;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
@@ -35,12 +36,9 @@ import org.springframework.data.mapping.model.AbstractPersistentPropertyUnitTest
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class SpelExpressionParameterProviderUnitTests {
|
||||
|
||||
@Mock
|
||||
SpELExpressionEvaluator evaluator;
|
||||
@Mock
|
||||
ParameterValueProvider<SamplePersistentProperty> delegate;
|
||||
@Mock
|
||||
ConversionService conversionService;
|
||||
@Mock SpELExpressionEvaluator evaluator;
|
||||
@Mock ParameterValueProvider<SamplePersistentProperty> delegate;
|
||||
@Mock ConversionService conversionService;
|
||||
|
||||
SpELExpressionParameterValueProvider<SamplePersistentProperty> provider;
|
||||
|
||||
@@ -54,6 +52,7 @@ public class SpelExpressionParameterProviderUnitTests {
|
||||
|
||||
parameter = mock(Parameter.class);
|
||||
when(parameter.hasSpelExpression()).thenReturn(true);
|
||||
when(parameter.getSpelExpression()).thenReturn(Optional.empty());
|
||||
when(parameter.getRawType()).thenReturn(Object.class);
|
||||
}
|
||||
|
||||
@@ -72,7 +71,7 @@ public class SpelExpressionParameterProviderUnitTests {
|
||||
@Test
|
||||
public void evaluatesSpELExpression() {
|
||||
|
||||
when(parameter.getSpelExpression()).thenReturn("expression");
|
||||
when(parameter.getSpelExpression()).thenReturn(Optional.of("expression"));
|
||||
|
||||
provider.getParameterValue(parameter);
|
||||
verify(delegate, times(0)).getParameterValue(parameter);
|
||||
@@ -114,7 +113,7 @@ public class SpelExpressionParameterProviderUnitTests {
|
||||
when(evaluator.evaluate(Mockito.anyString())).thenReturn("value");
|
||||
|
||||
Object result = provider.getParameterValue(parameter);
|
||||
assertThat(result, is((Object) "FOO"));
|
||||
assertThat(result).isEqualTo("FOO");
|
||||
verify(delegate, times(0)).getParameterValue(parameter);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ import org.springframework.data.annotation.AccessType.Type;
|
||||
*/
|
||||
public class TypeInOtherPackage {
|
||||
|
||||
private String privateField;
|
||||
@SuppressWarnings("unused") private String privateField;
|
||||
String packageDefaultField;
|
||||
protected String protectedField;
|
||||
public String publicField;
|
||||
@@ -38,10 +38,12 @@ public class TypeInOtherPackage {
|
||||
|
||||
@AccessType(Type.PROPERTY) private String publicProperty;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private String getPrivateProperty() {
|
||||
return privateProperty;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private void setPrivateProperty(String privateProperty) {
|
||||
this.privateProperty = privateProperty;
|
||||
}
|
||||
|
||||
14
src/test/java/org/springframework/data/projection/DefaultProjectionInformationUnitTests.java
Normal file → Executable file
14
src/test/java/org/springframework/data/projection/DefaultProjectionInformationUnitTests.java
Normal file → Executable file
@@ -15,9 +15,9 @@
|
||||
*/
|
||||
package org.springframework.data.projection;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.beans.FeatureDescriptor;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -36,7 +36,7 @@ public class DefaultProjectionInformationUnitTests {
|
||||
|
||||
ProjectionInformation information = new DefaultProjectionInformation(CustomerProjection.class);
|
||||
|
||||
assertThat(toNames(information.getInputProperties()), contains("firstname", "lastname"));
|
||||
assertThat(toNames(information.getInputProperties())).contains("firstname", "lastname");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-89
|
||||
@@ -44,7 +44,7 @@ public class DefaultProjectionInformationUnitTests {
|
||||
|
||||
ProjectionInformation information = new DefaultProjectionInformation(ExtendedProjection.class);
|
||||
|
||||
assertThat(toNames(information.getInputProperties()), hasItems("age", "firstname", "lastname"));
|
||||
assertThat(toNames(information.getInputProperties())).containsExactly("age", "firstname", "lastname");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-967
|
||||
@@ -52,14 +52,14 @@ public class DefaultProjectionInformationUnitTests {
|
||||
|
||||
ProjectionInformation information = new DefaultProjectionInformation(WithDefaultMethod.class);
|
||||
|
||||
assertThat(information.isClosed(), is(true));
|
||||
assertThat(toNames(information.getInputProperties()), hasItems("firstname"));
|
||||
assertThat(information.isClosed()).isTrue();
|
||||
assertThat(toNames(information.getInputProperties())).contains("firstname");
|
||||
}
|
||||
|
||||
private static List<String> toNames(List<PropertyDescriptor> descriptors) {
|
||||
|
||||
return descriptors.stream()//
|
||||
.map(it -> it.getName())//
|
||||
.map(FeatureDescriptor::getName)//
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
|
||||
13
src/test/java/org/springframework/data/projection/MapAccessingMethodInterceptorUnitTests.java
Normal file → Executable file
13
src/test/java/org/springframework/data/projection/MapAccessingMethodInterceptorUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.projection;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Collections;
|
||||
@@ -55,7 +54,7 @@ public class MapAccessingMethodInterceptorUnitTests {
|
||||
MapAccessingMethodInterceptor interceptor = new MapAccessingMethodInterceptor(map);
|
||||
Object result = interceptor.invoke(invocation);
|
||||
|
||||
assertThat(result, is((Object) map.toString()));
|
||||
assertThat(result).isEqualTo(map.toString());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-630
|
||||
@@ -68,8 +67,8 @@ public class MapAccessingMethodInterceptorUnitTests {
|
||||
|
||||
Object result = new MapAccessingMethodInterceptor(map).invoke(invocation);
|
||||
|
||||
assertThat(result, is(nullValue()));
|
||||
assertThat(map.get("name"), is((Object) "Foo"));
|
||||
assertThat(result).isNull();
|
||||
assertThat(map.get("name")).isEqualTo("Foo");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-630
|
||||
@@ -82,7 +81,7 @@ public class MapAccessingMethodInterceptorUnitTests {
|
||||
|
||||
Object result = new MapAccessingMethodInterceptor(map).invoke(invocation);
|
||||
|
||||
assertThat(result, is((Object) "Foo"));
|
||||
assertThat(result).isEqualTo("Foo");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-630
|
||||
@@ -92,7 +91,7 @@ public class MapAccessingMethodInterceptorUnitTests {
|
||||
|
||||
when(invocation.getMethod()).thenReturn(Sample.class.getMethod("getName"));
|
||||
|
||||
assertThat(new MapAccessingMethodInterceptor(map).invoke(invocation), is(nullValue()));
|
||||
assertThat(new MapAccessingMethodInterceptor(map).invoke(invocation)).isNull();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class) // DATACMNS-630
|
||||
|
||||
61
src/test/java/org/springframework/data/projection/ProjectingMethodInterceptorUnitTests.java
Normal file → Executable file
61
src/test/java/org/springframework/data/projection/ProjectingMethodInterceptorUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.projection;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -24,13 +23,10 @@ import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
import org.aopalliance.intercept.MethodInterceptor;
|
||||
import org.aopalliance.intercept.MethodInvocation;
|
||||
import org.hamcrest.Matcher;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
@@ -57,7 +53,7 @@ public class ProjectingMethodInterceptorUnitTests {
|
||||
when(invocation.getMethod()).thenReturn(Helper.class.getMethod("getHelper"));
|
||||
when(interceptor.invoke(invocation)).thenReturn("Foo");
|
||||
|
||||
assertThat(methodInterceptor.invoke(invocation), is(instanceOf(Helper.class)));
|
||||
assertThat(methodInterceptor.invoke(invocation)).isInstanceOf(Helper.class);
|
||||
}
|
||||
|
||||
@Test // DATAREST-221
|
||||
@@ -68,7 +64,7 @@ public class ProjectingMethodInterceptorUnitTests {
|
||||
when(invocation.getMethod()).thenReturn(Helper.class.getMethod("getString"));
|
||||
when(interceptor.invoke(invocation)).thenReturn("Foo");
|
||||
|
||||
assertThat(methodInterceptor.invoke(invocation), is((Object) "Foo"));
|
||||
assertThat(methodInterceptor.invoke(invocation)).isEqualTo("Foo");
|
||||
}
|
||||
|
||||
@Test // DATAREST-221
|
||||
@@ -78,7 +74,7 @@ public class ProjectingMethodInterceptorUnitTests {
|
||||
|
||||
when(interceptor.invoke(invocation)).thenReturn(null);
|
||||
|
||||
assertThat(methodInterceptor.invoke(invocation), is(nullValue()));
|
||||
assertThat(methodInterceptor.invoke(invocation)).isNull();
|
||||
}
|
||||
|
||||
@Test // DATAREST-221
|
||||
@@ -89,7 +85,7 @@ public class ProjectingMethodInterceptorUnitTests {
|
||||
when(invocation.getMethod()).thenReturn(Helper.class.getMethod("getPrimitive"));
|
||||
when(interceptor.invoke(invocation)).thenReturn(1L);
|
||||
|
||||
assertThat(methodInterceptor.invoke(invocation), is((Object) 1L));
|
||||
assertThat(methodInterceptor.invoke(invocation)).isEqualTo(1L);
|
||||
verify(factory, times(0)).createProjection((Class<?>) anyObject(), anyObject());
|
||||
}
|
||||
|
||||
@@ -98,14 +94,14 @@ public class ProjectingMethodInterceptorUnitTests {
|
||||
public void appliesProjectionToNonEmptySets() throws Throwable {
|
||||
|
||||
MethodInterceptor methodInterceptor = new ProjectingMethodInterceptor(new ProxyProjectionFactory(), interceptor);
|
||||
Object result = methodInterceptor.invoke(mockInvocationOf("getHelperCollection",
|
||||
Collections.singleton(mock(Helper.class))));
|
||||
Object result = methodInterceptor
|
||||
.invoke(mockInvocationOf("getHelperCollection", Collections.singleton(mock(Helper.class))));
|
||||
|
||||
assertThat(result, is(instanceOf(Set.class)));
|
||||
assertThat(result).isInstanceOf(Set.class);
|
||||
|
||||
Set<Object> projections = (Set<Object>) result;
|
||||
assertThat(projections, hasSize(1));
|
||||
assertThat(projections, hasItem(instanceOf(HelperProjection.class)));
|
||||
assertThat(projections).hasSize(1);
|
||||
assertThat(projections).hasOnlyElementsOfType(HelperProjection.class);
|
||||
}
|
||||
|
||||
@Test // DATAREST-394, DATAREST-408
|
||||
@@ -113,15 +109,15 @@ public class ProjectingMethodInterceptorUnitTests {
|
||||
public void appliesProjectionToNonEmptyLists() throws Throwable {
|
||||
|
||||
MethodInterceptor methodInterceptor = new ProjectingMethodInterceptor(new ProxyProjectionFactory(), interceptor);
|
||||
Object result = methodInterceptor.invoke(mockInvocationOf("getHelperList",
|
||||
Collections.singletonList(mock(Helper.class))));
|
||||
Object result = methodInterceptor
|
||||
.invoke(mockInvocationOf("getHelperList", Collections.singletonList(mock(Helper.class))));
|
||||
|
||||
assertThat(result, is(instanceOf(List.class)));
|
||||
assertThat(result).isInstanceOf(List.class);
|
||||
|
||||
List<Object> projections = (List<Object>) result;
|
||||
|
||||
assertThat(projections, hasSize(1));
|
||||
assertThat(projections, hasItem(instanceOf(HelperProjection.class)));
|
||||
assertThat(projections).hasSize(1);
|
||||
assertThat(projections).hasOnlyElementsOfType(HelperProjection.class);
|
||||
}
|
||||
|
||||
@Test // DATAREST-394, DATAREST-408
|
||||
@@ -131,12 +127,12 @@ public class ProjectingMethodInterceptorUnitTests {
|
||||
MethodInterceptor methodInterceptor = new ProjectingMethodInterceptor(new ProxyProjectionFactory(), interceptor);
|
||||
Object result = methodInterceptor.invoke(mockInvocationOf("getHelperArray", new Helper[] { mock(Helper.class) }));
|
||||
|
||||
assertThat(result, is(instanceOf(Collection.class)));
|
||||
assertThat(result).isInstanceOf(Collection.class);
|
||||
|
||||
Collection<Object> projections = (Collection<Object>) result;
|
||||
|
||||
assertThat(projections, hasSize(1));
|
||||
assertThat(projections, hasItem(instanceOf(HelperProjection.class)));
|
||||
assertThat(projections).hasSize(1);
|
||||
assertThat(projections).hasOnlyElementsOfType(HelperProjection.class);
|
||||
}
|
||||
|
||||
@Test // DATAREST-394, DATAREST-408
|
||||
@@ -145,18 +141,18 @@ public class ProjectingMethodInterceptorUnitTests {
|
||||
|
||||
MethodInterceptor methodInterceptor = new ProjectingMethodInterceptor(new ProxyProjectionFactory(), interceptor);
|
||||
|
||||
Object result = methodInterceptor.invoke(mockInvocationOf("getHelperMap",
|
||||
Collections.singletonMap("foo", mock(Helper.class))));
|
||||
Object result = methodInterceptor
|
||||
.invoke(mockInvocationOf("getHelperMap", Collections.singletonMap("foo", mock(Helper.class))));
|
||||
|
||||
assertThat(result, is(instanceOf(Map.class)));
|
||||
assertThat(result).isInstanceOf(Map.class);
|
||||
|
||||
Map<String, Object> projections = (Map<String, Object>) result;
|
||||
assertThat(projections.entrySet(), is(Matchers.<Entry<String, Object>> iterableWithSize(1)));
|
||||
assertThat(projections, hasEntry(is("foo"), instanceOf(HelperProjection.class)));
|
||||
|
||||
assertThat(projections).hasSize(1);
|
||||
assertThat(projections).matches(map -> map.get("foo") instanceof HelperProjection);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void returnsSingleElementCollectionForTargetThatReturnsNonCollection() throws Throwable {
|
||||
|
||||
MethodInterceptor methodInterceptor = new ProjectingMethodInterceptor(new ProxyProjectionFactory(), interceptor);
|
||||
@@ -164,9 +160,12 @@ public class ProjectingMethodInterceptorUnitTests {
|
||||
Helper reference = mock(Helper.class);
|
||||
Object result = methodInterceptor.invoke(mockInvocationOf("getHelperCollection", reference));
|
||||
|
||||
assertThat(result, is((Matcher<Object>) instanceOf(Collection.class)));
|
||||
assertThat((Collection<?>) result, hasSize(1));
|
||||
assertThat((Collection<Object>) result, hasItem(instanceOf(HelperProjection.class)));
|
||||
assertThat(result).isInstanceOf(Collection.class);
|
||||
|
||||
Collection<?> collection = (Collection<?>) result;
|
||||
|
||||
assertThat(collection).hasSize(1);
|
||||
assertThat(collection).hasOnlyElementsOfType(HelperProjection.class);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
7
src/test/java/org/springframework/data/projection/PropertyAccessingMethodInterceptorUnitTests.java
Normal file → Executable file
7
src/test/java/org/springframework/data/projection/PropertyAccessingMethodInterceptorUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.projection;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.aopalliance.intercept.MethodInterceptor;
|
||||
@@ -48,7 +47,7 @@ public class PropertyAccessingMethodInterceptorUnitTests {
|
||||
when(invocation.getMethod()).thenReturn(Projection.class.getMethod("getFirstname"));
|
||||
MethodInterceptor interceptor = new PropertyAccessingMethodInterceptor(source);
|
||||
|
||||
assertThat(interceptor.invoke(invocation), is((Object) "Dave"));
|
||||
assertThat(interceptor.invoke(invocation)).isEqualTo("Dave");
|
||||
}
|
||||
|
||||
@Test(expected = NotReadablePropertyException.class) // DATAREST-221
|
||||
@@ -85,7 +84,7 @@ public class PropertyAccessingMethodInterceptorUnitTests {
|
||||
|
||||
new PropertyAccessingMethodInterceptor(source).invoke(invocation);
|
||||
|
||||
assertThat(source.firstname, is((Object) "Carl"));
|
||||
assertThat(source.firstname).isEqualTo("Carl");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class) // DATACMNS-820
|
||||
|
||||
49
src/test/java/org/springframework/data/projection/ProxyProjectionFactoryUnitTests.java
Normal file → Executable file
49
src/test/java/org/springframework/data/projection/ProxyProjectionFactoryUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.projection;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Proxy;
|
||||
@@ -57,7 +56,7 @@ public class ProxyProjectionFactoryUnitTests {
|
||||
|
||||
@Test // DATACMNS-630
|
||||
public void returnsNullForNullSource() {
|
||||
assertThat(factory.createProjection(CustomerExcerpt.class, null), is(nullValue()));
|
||||
assertThat(factory.createProjection(CustomerExcerpt.class, null)).isNull();
|
||||
}
|
||||
|
||||
@Test // DATAREST-221, DATACMNS-630
|
||||
@@ -73,8 +72,8 @@ public class ProxyProjectionFactoryUnitTests {
|
||||
|
||||
CustomerExcerpt excerpt = factory.createProjection(CustomerExcerpt.class, customer);
|
||||
|
||||
assertThat(excerpt.getFirstname(), is("Dave"));
|
||||
assertThat(excerpt.getAddress().getZipCode(), is("ZIP"));
|
||||
assertThat(excerpt.getFirstname()).isEqualTo("Dave");
|
||||
assertThat(excerpt.getAddress().getZipCode()).isEqualTo("ZIP");
|
||||
}
|
||||
|
||||
@Test // DATAREST-221, DATACMNS-630
|
||||
@@ -83,8 +82,8 @@ public class ProxyProjectionFactoryUnitTests {
|
||||
|
||||
CustomerExcerpt proxy = factory.createProjection(CustomerExcerpt.class);
|
||||
|
||||
assertThat(proxy, is(instanceOf(TargetClassAware.class)));
|
||||
assertThat(((TargetClassAware) proxy).getTargetClass(), is(equalTo((Class) HashMap.class)));
|
||||
assertThat(proxy).isInstanceOf(TargetClassAware.class);
|
||||
assertThat(((TargetClassAware) proxy).getTargetClass()).isEqualTo(HashMap.class);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class) // DATAREST-221, DATACMNS-630
|
||||
@@ -106,11 +105,11 @@ public class ProxyProjectionFactoryUnitTests {
|
||||
|
||||
CustomerExcerpt projection = factory.createProjection(CustomerExcerpt.class, source);
|
||||
|
||||
assertThat(projection.getFirstname(), is("Dave"));
|
||||
assertThat(projection.getFirstname()).isEqualTo("Dave");
|
||||
|
||||
AddressExcerpt address = projection.getAddress();
|
||||
assertThat(address, is(notNullValue()));
|
||||
assertThat(address.getZipCode(), is("ZIP"));
|
||||
assertThat(address).isNotNull();
|
||||
assertThat(address.getZipCode()).isEqualTo("ZIP");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-630
|
||||
@@ -118,10 +117,10 @@ public class ProxyProjectionFactoryUnitTests {
|
||||
|
||||
CustomerProxy proxy = factory.createProjection(CustomerProxy.class);
|
||||
|
||||
assertThat(proxy, is(notNullValue()));
|
||||
assertThat(proxy).isNotNull();
|
||||
|
||||
proxy.setFirstname("Dave");
|
||||
assertThat(proxy.getFirstname(), is("Dave"));
|
||||
assertThat(proxy.getFirstname()).isEqualTo("Dave");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-630
|
||||
@@ -130,7 +129,7 @@ public class ProxyProjectionFactoryUnitTests {
|
||||
ProjectionInformation projectionInformation = factory.getProjectionInformation(CustomerExcerpt.class);
|
||||
List<PropertyDescriptor> result = projectionInformation.getInputProperties();
|
||||
|
||||
assertThat(result, hasSize(6));
|
||||
assertThat(result).hasSize(6);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-655
|
||||
@@ -141,8 +140,8 @@ public class ProxyProjectionFactoryUnitTests {
|
||||
Advised advised = (Advised) ReflectionTestUtils.getField(Proxy.getInvocationHandler(excerpt), "advised");
|
||||
Advisor[] advisors = advised.getAdvisors();
|
||||
|
||||
assertThat(advisors.length, is(greaterThan(0)));
|
||||
assertThat(advisors[0].getAdvice(), is(instanceOf(DefaultMethodInvokingMethodInterceptor.class)));
|
||||
assertThat(advisors.length).isGreaterThan(0);
|
||||
assertThat(advisors[0].getAdvice()).isInstanceOf(DefaultMethodInvokingMethodInterceptor.class);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-648
|
||||
@@ -150,8 +149,8 @@ public class ProxyProjectionFactoryUnitTests {
|
||||
|
||||
CustomerExcerpt excerpt = factory.createProjection(CustomerExcerpt.class);
|
||||
|
||||
assertThat(excerpt, is(instanceOf(TargetAware.class)));
|
||||
assertThat(((TargetAware) excerpt).getTarget(), is(instanceOf(Map.class)));
|
||||
assertThat(excerpt).isInstanceOf(TargetAware.class);
|
||||
assertThat(((TargetAware) excerpt).getTarget()).isInstanceOf(Map.class);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-722
|
||||
@@ -162,7 +161,7 @@ public class ProxyProjectionFactoryUnitTests {
|
||||
|
||||
CustomerExcerpt excerpt = factory.createProjection(CustomerExcerpt.class, customer);
|
||||
|
||||
assertThat(excerpt.getPicture(), is(customer.picture));
|
||||
assertThat(excerpt.getPicture()).isEqualTo(customer.picture);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-722
|
||||
@@ -177,7 +176,7 @@ public class ProxyProjectionFactoryUnitTests {
|
||||
|
||||
CustomerExcerpt excerpt = factory.createProjection(CustomerExcerpt.class, customer);
|
||||
|
||||
assertThat(excerpt.getShippingAddresses(), is(arrayWithSize(1)));
|
||||
assertThat(excerpt.getShippingAddresses()).hasSize(1);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-782
|
||||
@@ -188,7 +187,7 @@ public class ProxyProjectionFactoryUnitTests {
|
||||
|
||||
CustomerExcerpt excerpt = factory.createProjection(CustomerExcerpt.class, customer);
|
||||
|
||||
assertThat(excerpt.getId(), is(customer.id.toString()));
|
||||
assertThat(excerpt.getId()).isEqualTo(customer.id.toString());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-89
|
||||
@@ -196,8 +195,8 @@ public class ProxyProjectionFactoryUnitTests {
|
||||
|
||||
ProjectionInformation information = factory.getProjectionInformation(CustomerExcerpt.class);
|
||||
|
||||
assertThat(information.getType(), is(typeCompatibleWith(CustomerExcerpt.class)));
|
||||
assertThat(information.isClosed(), is(true));
|
||||
assertThat(information.getType()).isEqualTo(CustomerExcerpt.class);
|
||||
assertThat(information.isClosed()).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-829
|
||||
@@ -208,9 +207,9 @@ public class ProxyProjectionFactoryUnitTests {
|
||||
|
||||
Map<String, Object> data = factory.createProjection(CustomerExcerpt.class, customer).getData();
|
||||
|
||||
assertThat(data, is(notNullValue()));
|
||||
assertThat(data.containsKey("key"), is(true));
|
||||
assertThat(data.get("key"), is(nullValue()));
|
||||
assertThat(data).isNotNull();
|
||||
assertThat(data.containsKey("key")).isTrue();
|
||||
assertThat(data.get("key")).isNull();
|
||||
}
|
||||
|
||||
static class Customer {
|
||||
|
||||
12
src/test/java/org/springframework/data/projection/SpelAwareProxyProjectionFactoryUnitTests.java
Normal file → Executable file
12
src/test/java/org/springframework/data/projection/SpelAwareProxyProjectionFactoryUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.projection;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -53,7 +52,7 @@ public class SpelAwareProxyProjectionFactoryUnitTests {
|
||||
customer.lastname = "Matthews";
|
||||
|
||||
CustomerExcerpt excerpt = factory.createProjection(CustomerExcerpt.class, customer);
|
||||
assertThat(excerpt.getFullName(), is("Dave Matthews"));
|
||||
assertThat(excerpt.getFullName()).isEqualTo("Dave Matthews");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-630
|
||||
@@ -61,8 +60,7 @@ public class SpelAwareProxyProjectionFactoryUnitTests {
|
||||
|
||||
List<String> properties = factory.getInputProperties(CustomerExcerpt.class);
|
||||
|
||||
assertThat(properties, hasSize(1));
|
||||
assertThat(properties, hasItem("firstname"));
|
||||
assertThat(properties).containsExactly("firstname");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-89
|
||||
@@ -70,7 +68,7 @@ public class SpelAwareProxyProjectionFactoryUnitTests {
|
||||
|
||||
ProjectionInformation information = factory.getProjectionInformation(CustomerExcerpt.class);
|
||||
|
||||
assertThat(information.isClosed(), is(false));
|
||||
assertThat(information.isClosed()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-820
|
||||
@@ -82,7 +80,7 @@ public class SpelAwareProxyProjectionFactoryUnitTests {
|
||||
CustomerExcerpt excerpt = factory.createProjection(CustomerExcerpt.class, customer);
|
||||
excerpt.setFirstname("Carl");
|
||||
|
||||
assertThat(customer.firstname, is("Carl"));
|
||||
assertThat(customer.firstname).isEqualTo("Carl");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-820
|
||||
|
||||
9
src/test/java/org/springframework/data/projection/SpelEvaluatingMethodInterceptorUnitTests.java
Normal file → Executable file
9
src/test/java/org/springframework/data/projection/SpelEvaluatingMethodInterceptorUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.projection;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
@@ -54,7 +53,7 @@ public class SpelEvaluatingMethodInterceptorUnitTests {
|
||||
MethodInterceptor interceptor = new SpelEvaluatingMethodInterceptor(delegate, new Target(), null, parser,
|
||||
Projection.class);
|
||||
|
||||
assertThat(interceptor.invoke(invocation), is((Object) "property"));
|
||||
assertThat(interceptor.invoke(invocation)).isEqualTo("property");
|
||||
}
|
||||
|
||||
@Test // DATAREST-221, DATACMNS-630
|
||||
@@ -68,7 +67,7 @@ public class SpelEvaluatingMethodInterceptorUnitTests {
|
||||
SpelEvaluatingMethodInterceptor interceptor = new SpelEvaluatingMethodInterceptor(delegate, new Target(), factory,
|
||||
parser, Projection.class);
|
||||
|
||||
assertThat(interceptor.invoke(invocation), is((Object) "value"));
|
||||
assertThat(interceptor.invoke(invocation)).isEqualTo("value");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-630
|
||||
@@ -106,7 +105,7 @@ public class SpelEvaluatingMethodInterceptorUnitTests {
|
||||
SpelEvaluatingMethodInterceptor interceptor = new SpelEvaluatingMethodInterceptor(delegate, map,
|
||||
new DefaultListableBeanFactory(), parser, Projection.class);
|
||||
|
||||
assertThat(interceptor.invoke(invocation), is((Object) "Dave"));
|
||||
assertThat(interceptor.invoke(invocation)).isEqualTo("Dave");
|
||||
}
|
||||
|
||||
interface Projection {
|
||||
|
||||
7
src/test/java/org/springframework/data/querydsl/QPageRequestUnitTests.java
Normal file → Executable file
7
src/test/java/org/springframework/data/querydsl/QPageRequestUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.querydsl;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.AbstractPageRequest;
|
||||
@@ -41,7 +40,7 @@ public class QPageRequestUnitTests extends AbstractPageRequestUnitTests {
|
||||
QUser user = QUser.user;
|
||||
QPageRequest pageRequest = new QPageRequest(0, 10, user.firstname.asc());
|
||||
|
||||
assertThat(pageRequest.getSort(), is(new QSort(user.firstname.asc())));
|
||||
assertThat(pageRequest.getSort()).isEqualTo(new QSort(user.firstname.asc()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -50,6 +49,6 @@ public class QPageRequestUnitTests extends AbstractPageRequestUnitTests {
|
||||
QUser user = QUser.user;
|
||||
QPageRequest pageRequest = new QPageRequest(0, 10, new QSort(user.firstname.asc()));
|
||||
|
||||
assertThat(pageRequest.getSort(), is(new QSort(user.firstname.asc())));
|
||||
assertThat(pageRequest.getSort()).isEqualTo(new QSort(user.firstname.asc()));
|
||||
}
|
||||
}
|
||||
|
||||
66
src/test/java/org/springframework/data/querydsl/QSortUnitTests.java
Normal file → Executable file
66
src/test/java/org/springframework/data/querydsl/QSortUnitTests.java
Normal file → Executable file
@@ -15,15 +15,13 @@
|
||||
*/
|
||||
package org.springframework.data.querydsl;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.querydsl.QQSortUnitTests_WrapperToWrapWrapperForUserWrapper.*;
|
||||
import static org.springframework.data.querydsl.QQSortUnitTests_WrapperToWrapWrapperForUserWrapper_WrapperForUserWrapper.*;
|
||||
import static org.springframework.data.querydsl.QQSortUnitTests_WrapperToWrapWrapperForUserWrapper_WrapperForUserWrapper_UserWrapper.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
@@ -53,58 +51,54 @@ public class QSortUnitTests {
|
||||
new QSort((List<OrderSpecifier<?>>) null);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test // DATACMNS-402
|
||||
public void sortBySingleProperty() {
|
||||
|
||||
QUser user = QUser.user;
|
||||
QSort qsort = new QSort(user.firstname.asc());
|
||||
|
||||
assertThat(qsort.getOrderSpecifiers().size(), is(1));
|
||||
assertThat((OrderSpecifier<String>) qsort.getOrderSpecifiers().get(0), is(user.firstname.asc()));
|
||||
assertThat(qsort.getOrderFor("firstname"), is(new Sort.Order(Sort.Direction.ASC, "firstname")));
|
||||
assertThat(qsort.getOrderSpecifiers()).hasSize(1);
|
||||
assertThat(qsort.getOrderSpecifiers().get(0)).isEqualTo(user.firstname.asc());
|
||||
assertThat(qsort.getOrderFor("firstname")).isEqualTo(new Sort.Order(Sort.Direction.ASC, "firstname"));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test // DATACMNS-402
|
||||
public void sortByMultiplyProperties() {
|
||||
|
||||
QUser user = QUser.user;
|
||||
QSort qsort = new QSort(user.firstname.asc(), user.lastname.desc());
|
||||
|
||||
assertThat(qsort.getOrderSpecifiers().size(), is(2));
|
||||
assertThat((OrderSpecifier<String>) qsort.getOrderSpecifiers().get(0), is(user.firstname.asc()));
|
||||
assertThat((OrderSpecifier<String>) qsort.getOrderSpecifiers().get(1), is(user.lastname.desc()));
|
||||
assertThat(qsort.getOrderFor("firstname"), is(new Sort.Order(Sort.Direction.ASC, "firstname")));
|
||||
assertThat(qsort.getOrderFor("lastname"), is(new Sort.Order(Sort.Direction.DESC, "lastname")));
|
||||
assertThat(qsort.getOrderSpecifiers()).hasSize(2);
|
||||
assertThat(qsort.getOrderSpecifiers().get(0)).isEqualTo(user.firstname.asc());
|
||||
assertThat(qsort.getOrderSpecifiers().get(1)).isEqualTo(user.lastname.desc());
|
||||
assertThat(qsort.getOrderFor("firstname")).isEqualTo(new Sort.Order(Sort.Direction.ASC, "firstname"));
|
||||
assertThat(qsort.getOrderFor("lastname")).isEqualTo(new Sort.Order(Sort.Direction.DESC, "lastname"));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test // DATACMNS-402
|
||||
public void sortByMultiplyPropertiesWithAnd() {
|
||||
|
||||
QUser user = QUser.user;
|
||||
QSort qsort = new QSort(user.firstname.asc()).and(new QSort(user.lastname.desc()));
|
||||
|
||||
assertThat(qsort.getOrderSpecifiers().size(), is(2));
|
||||
assertThat((OrderSpecifier<String>) qsort.getOrderSpecifiers().get(0), is(user.firstname.asc()));
|
||||
assertThat((OrderSpecifier<String>) qsort.getOrderSpecifiers().get(1), is(user.lastname.desc()));
|
||||
assertThat(qsort.getOrderFor("firstname"), is(new Sort.Order(Sort.Direction.ASC, "firstname")));
|
||||
assertThat(qsort.getOrderFor("lastname"), is(new Sort.Order(Sort.Direction.DESC, "lastname")));
|
||||
assertThat(qsort.getOrderSpecifiers()).hasSize(2);
|
||||
assertThat(qsort.getOrderSpecifiers().get(0)).isEqualTo(user.firstname.asc());
|
||||
assertThat(qsort.getOrderSpecifiers().get(1)).isEqualTo(user.lastname.desc());
|
||||
assertThat(qsort.getOrderFor("firstname")).isEqualTo(new Sort.Order(Sort.Direction.ASC, "firstname"));
|
||||
assertThat(qsort.getOrderFor("lastname")).isEqualTo(new Sort.Order(Sort.Direction.DESC, "lastname"));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test // DATACMNS-402
|
||||
public void sortByMultiplyPropertiesWithAndAndVarArgs() {
|
||||
|
||||
QUser user = QUser.user;
|
||||
QSort qsort = new QSort(user.firstname.asc()).and(user.lastname.desc());
|
||||
|
||||
assertThat(qsort.getOrderSpecifiers().size(), is(2));
|
||||
assertThat((OrderSpecifier<String>) qsort.getOrderSpecifiers().get(0), is(user.firstname.asc()));
|
||||
assertThat((OrderSpecifier<String>) qsort.getOrderSpecifiers().get(1), is(user.lastname.desc()));
|
||||
assertThat(qsort.getOrderFor("firstname"), is(new Sort.Order(Sort.Direction.ASC, "firstname")));
|
||||
assertThat(qsort.getOrderFor("lastname"), is(new Sort.Order(Sort.Direction.DESC, "lastname")));
|
||||
assertThat(qsort.getOrderSpecifiers()).hasSize(2);
|
||||
assertThat(qsort.getOrderSpecifiers().get(0)).isEqualTo(user.firstname.asc());
|
||||
assertThat(qsort.getOrderSpecifiers().get(1)).isEqualTo(user.lastname.desc());
|
||||
assertThat(qsort.getOrderFor("firstname")).isEqualTo(new Sort.Order(Sort.Direction.ASC, "firstname"));
|
||||
assertThat(qsort.getOrderFor("lastname")).isEqualTo(new Sort.Order(Sort.Direction.DESC, "lastname"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-402
|
||||
@@ -115,8 +109,8 @@ public class QSortUnitTests {
|
||||
|
||||
Sort sort = qsort;
|
||||
|
||||
assertThat(sort.getOrderFor("firstname"), is(new Sort.Order(Sort.Direction.ASC, "firstname")));
|
||||
assertThat(sort.getOrderFor("lastname"), is(new Sort.Order(Sort.Direction.DESC, "lastname")));
|
||||
assertThat(sort.getOrderFor("firstname")).isEqualTo(new Sort.Order(Sort.Direction.ASC, "firstname"));
|
||||
assertThat(sort.getOrderFor("lastname")).isEqualTo(new Sort.Order(Sort.Direction.DESC, "lastname"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-402
|
||||
@@ -126,8 +120,8 @@ public class QSortUnitTests {
|
||||
QSort sort = new QSort(user.firstname.asc());
|
||||
|
||||
Sort result = sort.and(new Sort(Direction.ASC, "lastname"));
|
||||
assertThat(result, is(Matchers.<Order> iterableWithSize(2)));
|
||||
assertThat(result, hasItems(new Order(Direction.ASC, "lastname"), new Order(Direction.ASC, "firstname")));
|
||||
assertThat(result).hasSize(2);
|
||||
assertThat(result).contains(new Order(Direction.ASC, "lastname"), new Order(Direction.ASC, "firstname"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-566
|
||||
@@ -137,9 +131,9 @@ public class QSortUnitTests {
|
||||
QSort sort = new QSort(user.dateOfBirth.yearMonth().asc());
|
||||
|
||||
Sort result = sort.and(new Sort(Direction.ASC, "lastname"));
|
||||
assertThat(result, is(Matchers.<Order> iterableWithSize(2)));
|
||||
assertThat(result, hasItems(new Order(Direction.ASC, "lastname"),
|
||||
new Order(Direction.ASC, user.dateOfBirth.yearMonth().toString())));
|
||||
assertThat(result).hasSize(2);
|
||||
assertThat(result).contains(new Order(Direction.ASC, "lastname"),
|
||||
new Order(Direction.ASC, user.dateOfBirth.yearMonth().toString()));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-621
|
||||
@@ -147,7 +141,7 @@ public class QSortUnitTests {
|
||||
|
||||
QSort sort = new QSort(userWrapper.user.firstname.asc());
|
||||
|
||||
assertThat(sort, hasItems(new Order(Direction.ASC, "user.firstname")));
|
||||
assertThat(sort).contains(new Order(Direction.ASC, "user.firstname"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-621
|
||||
@@ -155,7 +149,7 @@ public class QSortUnitTests {
|
||||
|
||||
QSort sort = new QSort(wrapperForUserWrapper.wrapper.user.firstname.asc());
|
||||
|
||||
assertThat(sort, hasItems(new Order(Direction.ASC, "wrapper.user.firstname")));
|
||||
assertThat(sort).contains(new Order(Direction.ASC, "wrapper.user.firstname"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-621
|
||||
@@ -163,7 +157,7 @@ public class QSortUnitTests {
|
||||
|
||||
QSort sort = new QSort(wrapperToWrapWrapperForUserWrapper.wrapperForUserWrapper.wrapper.user.firstname.asc());
|
||||
|
||||
assertThat(sort, hasItems(new Order(Direction.ASC, "wrapperForUserWrapper.wrapper.user.firstname")));
|
||||
assertThat(sort).contains(new Order(Direction.ASC, "wrapperForUserWrapper.wrapper.user.firstname"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-755
|
||||
@@ -173,7 +167,7 @@ public class QSortUnitTests {
|
||||
|
||||
QSort sort = new QSort(new OrderSpecifier<String>(com.querydsl.core.types.Order.ASC, path));
|
||||
|
||||
assertThat(sort, hasItems(new Order(Direction.ASC, "firstname")));
|
||||
assertThat(sort).contains(new Order(Direction.ASC, "firstname"));
|
||||
}
|
||||
|
||||
@com.querydsl.core.annotations.QueryEntity
|
||||
|
||||
11
src/test/java/org/springframework/data/querydsl/QueryDslUtilsUnitTests.java
Normal file → Executable file
11
src/test/java/org/springframework/data/querydsl/QueryDslUtilsUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.querydsl;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.data.querydsl.QueryDslUtils.*;
|
||||
|
||||
import org.junit.Test;
|
||||
@@ -30,14 +29,14 @@ public class QueryDslUtilsUnitTests {
|
||||
|
||||
@Test // DATACMNS-883
|
||||
public void rendersDotPathForPathTraversalContainingAnyExpression() {
|
||||
assertThat(toDotPath(QUser.user.addresses.any().street), is("addresses.street"));
|
||||
assertThat(QueryDslUtils.toDotPath(QUser.user.addresses.any().street)).isEqualTo("addresses.street");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-941
|
||||
public void skipsIntermediateDelegates() {
|
||||
|
||||
assertThat(toDotPath(QUser.user.as(QSpecialUser.class).as(QSpecialUser.class).specialProperty),
|
||||
is("specialProperty"));
|
||||
assertThat(toDotPath(QUser.user.as(QSpecialUser.class).specialProperty), is("specialProperty"));
|
||||
assertThat(toDotPath(QUser.user.as(QSpecialUser.class).as(QSpecialUser.class).specialProperty))
|
||||
.isEqualTo("specialProperty");
|
||||
assertThat(toDotPath(QUser.user.as(QSpecialUser.class).specialProperty)).isEqualTo("specialProperty");
|
||||
}
|
||||
}
|
||||
|
||||
7
src/test/java/org/springframework/data/querydsl/QuerydslRepositoryInvokerAdapterUnitTests.java
Normal file → Executable file
7
src/test/java/org/springframework/data/querydsl/QuerydslRepositoryInvokerAdapterUnitTests.java
Normal file → Executable file
@@ -20,7 +20,6 @@ import static org.mockito.Mockito.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
@@ -76,7 +75,7 @@ public class QuerydslRepositoryInvokerAdapterUnitTests {
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
@SuppressWarnings({ "deprecation", "unchecked" })
|
||||
@SuppressWarnings("unchecked")
|
||||
public void forwardsMethodsToDelegate() {
|
||||
|
||||
adapter.hasDeleteMethod();
|
||||
@@ -97,10 +96,6 @@ public class QuerydslRepositoryInvokerAdapterUnitTests {
|
||||
adapter.invokeFindOne(any(Serializable.class));
|
||||
verify(delegate, times(1)).invokeFindOne(any(Serializable.class));
|
||||
|
||||
adapter.invokeQueryMethod(any(Method.class), any(Map.class), any(Pageable.class), any(Sort.class));
|
||||
verify(delegate, times(1)).invokeQueryMethod(any(Method.class), any(Map.class), any(Pageable.class),
|
||||
any(Sort.class));
|
||||
|
||||
adapter.invokeQueryMethod(any(Method.class), (MultiValueMap<String, String>) any(MultiValueMap.class),
|
||||
any(Pageable.class), any(Sort.class));
|
||||
verify(delegate, times(1)).invokeQueryMethod(any(Method.class),
|
||||
|
||||
9
src/test/java/org/springframework/data/querydsl/SimpleEntityPathResolverUnitTests.java
Normal file → Executable file
9
src/test/java/org/springframework/data/querydsl/SimpleEntityPathResolverUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.querydsl;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -33,15 +32,13 @@ public class SimpleEntityPathResolverUnitTests {
|
||||
|
||||
@Test
|
||||
public void createsRepositoryFromDomainClassCorrectly() throws Exception {
|
||||
|
||||
assertThat((QUser) resolver.createPath(User.class), isA(QUser.class));
|
||||
assertThat(resolver.createPath(User.class)).isInstanceOf(QUser.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resolvesEntityPathForInnerClassCorrectly() throws Exception {
|
||||
|
||||
assertThat((QSimpleEntityPathResolverUnitTests_NamedUser) resolver.createPath(NamedUser.class),
|
||||
isA(QSimpleEntityPathResolverUnitTests_NamedUser.class));
|
||||
assertThat(resolver.createPath(NamedUser.class)).isInstanceOf(QSimpleEntityPathResolverUnitTests_NamedUser.class);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
|
||||
69
src/test/java/org/springframework/data/querydsl/binding/QuerydslBindingsFactoryUnitTests.java
Normal file → Executable file
69
src/test/java/org/springframework/data/querydsl/binding/QuerydslBindingsFactoryUnitTests.java
Normal file → Executable file
@@ -15,16 +15,14 @@
|
||||
*/
|
||||
package org.springframework.data.querydsl.binding;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
|
||||
import org.springframework.data.querydsl.QUser;
|
||||
import org.springframework.data.querydsl.SimpleEntityPathResolver;
|
||||
@@ -37,7 +35,6 @@ import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import com.querydsl.core.types.Path;
|
||||
import com.querydsl.core.types.Predicate;
|
||||
import com.querydsl.core.types.dsl.StringPath;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link QuerydslBindingsFactory}.
|
||||
@@ -49,8 +46,6 @@ public class QuerydslBindingsFactoryUnitTests {
|
||||
|
||||
static final TypeInformation<?> USER_TYPE = ClassTypeInformation.from(User.class);
|
||||
|
||||
public @Rule ExpectedException exception = ExpectedException.none();
|
||||
|
||||
QuerydslBindingsFactory factory;
|
||||
|
||||
@Before
|
||||
@@ -65,17 +60,19 @@ public class QuerydslBindingsFactoryUnitTests {
|
||||
Repositories repositories = mock(Repositories.class);
|
||||
|
||||
when(repositories.hasRepositoryFor(User.class)).thenReturn(true);
|
||||
when(repositories.getRepositoryFor(User.class)).thenReturn(new SampleRepo());
|
||||
when(repositories.getRepositoryFor(User.class)).thenReturn(Optional.of(new SampleRepo()));
|
||||
|
||||
QuerydslBindingsFactory factory = new QuerydslBindingsFactory(SimpleEntityPathResolver.INSTANCE);
|
||||
ReflectionTestUtils.setField(factory, "repositories", repositories);
|
||||
ReflectionTestUtils.setField(factory, "repositories", Optional.of(repositories));
|
||||
|
||||
QuerydslBindings bindings = factory.createBindingsFor(null, USER_TYPE);
|
||||
MultiValueBinding<Path<Object>, Object> binding = bindings
|
||||
QuerydslBindings bindings = factory.createBindingsFor(USER_TYPE, Optional.empty());
|
||||
Optional<MultiValueBinding<Path<Object>, Object>> binding = bindings
|
||||
.getBindingForPath(PropertyPathInformation.of("firstname", User.class));
|
||||
|
||||
assertThat(binding.bind((Path) QUser.user.firstname, Collections.singleton("rand")),
|
||||
is((Predicate) QUser.user.firstname.contains("rand")));
|
||||
assertThat(binding).hasValueSatisfying(it -> {
|
||||
Optional<Predicate> bind = it.bind((Path) QUser.user.firstname, Collections.singleton("rand"));
|
||||
assertThat(bind).hasValue(QUser.user.firstname.contains("rand"));
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
@@ -86,45 +83,34 @@ public class QuerydslBindingsFactoryUnitTests {
|
||||
when(beanFactory.getBean(SpecificBinding.class)).thenReturn(new SpecificBinding());
|
||||
|
||||
QuerydslBindingsFactory factory = new QuerydslBindingsFactory(SimpleEntityPathResolver.INSTANCE);
|
||||
ReflectionTestUtils.setField(factory, "beanFactory", beanFactory);
|
||||
ReflectionTestUtils.setField(factory, "beanFactory", Optional.of(beanFactory));
|
||||
|
||||
QuerydslBindings bindings = factory.createBindingsFor(SpecificBinding.class, USER_TYPE);
|
||||
MultiValueBinding<Path<Object>, Object> binding = bindings
|
||||
QuerydslBindings bindings = factory.createBindingsFor(USER_TYPE, Optional.of(SpecificBinding.class));
|
||||
Optional<MultiValueBinding<Path<Object>, Object>> binding = bindings
|
||||
.getBindingForPath(PropertyPathInformation.of("firstname", User.class));
|
||||
|
||||
assertThat(binding.bind((Path) QUser.user.firstname, Collections.singleton("rand")),
|
||||
is((Predicate) QUser.user.firstname.eq("RAND")));
|
||||
assertThat(binding).hasValueSatisfying(it -> {
|
||||
Optional<Predicate> bind = it.bind((Path) QUser.user.firstname, Collections.singleton("rand"));
|
||||
assertThat(bind).hasValue(QUser.user.firstname.eq("RAND"));
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
public void rejectsPredicateResolutionIfDomainTypeCantBeAutoDetected() {
|
||||
|
||||
exception.expect(IllegalStateException.class);
|
||||
exception.expectMessage(QuerydslPredicate.class.getSimpleName());
|
||||
exception.expectMessage("root");
|
||||
assertThatExceptionOfType(IllegalStateException.class)//
|
||||
.isThrownBy(() -> factory.createBindingsFor(ClassTypeInformation.from(ModelAndView.class), Optional.empty()))//
|
||||
.withMessageContaining(QuerydslPredicate.class.getSimpleName())//
|
||||
.withMessageContaining("root");
|
||||
|
||||
factory.createBindingsFor(null, ClassTypeInformation.from(ModelAndView.class));
|
||||
}
|
||||
|
||||
static class SpecificBinding implements QuerydslBinderCustomizer<QUser> {
|
||||
|
||||
public void customize(QuerydslBindings bindings, QUser user) {
|
||||
|
||||
bindings.bind(user.firstname).first(new SingleValueBinding<StringPath, String>() {
|
||||
|
||||
@Override
|
||||
public Predicate bind(StringPath path, String value) {
|
||||
return path.eq(value.toUpperCase());
|
||||
}
|
||||
});
|
||||
|
||||
bindings.bind(user.lastname).first(new SingleValueBinding<StringPath, String>() {
|
||||
|
||||
@Override
|
||||
public Predicate bind(StringPath path, String value) {
|
||||
return path.toLowerCase().eq(value);
|
||||
}
|
||||
});
|
||||
bindings.bind(user.firstname).firstOptional((path, value) -> value.map(it -> path.eq(it.toUpperCase())));
|
||||
bindings.bind(user.lastname).firstOptional((path, value) -> value.map(it -> path.toLowerCase().eq(it)));
|
||||
|
||||
bindings.excluding(user.address);
|
||||
}
|
||||
@@ -134,14 +120,7 @@ public class QuerydslBindingsFactoryUnitTests {
|
||||
|
||||
@Override
|
||||
public void customize(QuerydslBindings bindings, QUser user) {
|
||||
|
||||
bindings.bind(QUser.user.firstname).first(new SingleValueBinding<StringPath, String>() {
|
||||
|
||||
@Override
|
||||
public Predicate bind(StringPath path, String value) {
|
||||
return path.contains(value);
|
||||
}
|
||||
});
|
||||
bindings.bind(QUser.user.firstname).firstOptional((path, value) -> value.map(it -> path.contains(it)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
101
src/test/java/org/springframework/data/querydsl/binding/QuerydslBindingsUnitTests.java
Normal file → Executable file
101
src/test/java/org/springframework/data/querydsl/binding/QuerydslBindingsUnitTests.java
Normal file → Executable file
@@ -15,8 +15,9 @@
|
||||
*/
|
||||
package org.springframework.data.querydsl.binding;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
@@ -26,7 +27,6 @@ import org.springframework.data.querydsl.QUser;
|
||||
import org.springframework.data.querydsl.SimpleEntityPathResolver;
|
||||
import org.springframework.data.querydsl.User;
|
||||
import org.springframework.data.util.ClassTypeInformation;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import com.querydsl.core.types.Path;
|
||||
import com.querydsl.core.types.Predicate;
|
||||
@@ -43,13 +43,8 @@ public class QuerydslBindingsUnitTests {
|
||||
QuerydslPredicateBuilder builder;
|
||||
QuerydslBindings bindings;
|
||||
|
||||
static final SingleValueBinding<StringPath, String> CONTAINS_BINDING = new SingleValueBinding<StringPath, String>() {
|
||||
|
||||
@Override
|
||||
public Predicate bind(StringPath path, String value) {
|
||||
return path.contains(value);
|
||||
}
|
||||
};
|
||||
static final SingleValueBinding<StringPath, String> CONTAINS_BINDING = (path, value) -> Optional
|
||||
.of(path.contains(value));
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
@@ -68,7 +63,7 @@ public class QuerydslBindingsUnitTests {
|
||||
|
||||
PathInformation path = PropertyPathInformation.of("lastname", User.class);
|
||||
|
||||
assertThat(bindings.getBindingForPath(path), nullValue());
|
||||
assertThat(bindings.getBindingForPath(path)).isNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
@@ -97,93 +92,92 @@ public class QuerydslBindingsUnitTests {
|
||||
bindings.bind(String.class).first(CONTAINS_BINDING);
|
||||
|
||||
PathInformation path = PropertyPathInformation.of("address.street", User.class);
|
||||
|
||||
assertAdapterWithTargetBinding(bindings.getBindingForPath(path), CONTAINS_BINDING);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
public void propertyNotExplicitlyIncludedAndWithoutTypeBindingIsInvisible() {
|
||||
public void propertyNotExplicitlyIncludedAndWithoutTypeBindingIsNotAvailable() {
|
||||
|
||||
bindings.bind(String.class).first(CONTAINS_BINDING);
|
||||
|
||||
PathInformation path = PropertyPathInformation.of("inceptionYear", User.class);
|
||||
|
||||
assertThat(bindings.getBindingForPath(path), nullValue());
|
||||
assertThat(bindings.getBindingForPath(path)).isNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
public void pathIsVisibleIfTypeBasedBindingWasRegistered() {
|
||||
public void pathIsAvailableIfTypeBasedBindingWasRegistered() {
|
||||
|
||||
bindings.bind(String.class).first(CONTAINS_BINDING);
|
||||
|
||||
assertThat(bindings.isPathAvailable("inceptionYear", User.class), is(true));
|
||||
assertThat(bindings.isPathAvailable("inceptionYear", User.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
public void explicitlyIncludedPathIsVisible() {
|
||||
public void explicitlyIncludedPathIsAvailable() {
|
||||
|
||||
bindings.including(QUser.user.inceptionYear);
|
||||
|
||||
assertThat(bindings.isPathAvailable("inceptionYear", User.class), is(true));
|
||||
assertThat(bindings.isPathAvailable("inceptionYear", User.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
public void notExplicitlyIncludedPathIsInvisible() {
|
||||
public void notExplicitlyIncludedPathIsNotAvailable() {
|
||||
|
||||
bindings.including(QUser.user.inceptionYear);
|
||||
|
||||
assertThat(bindings.isPathAvailable("firstname", User.class), is(false));
|
||||
assertThat(bindings.isPathAvailable("firstname", User.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
public void excludedPathIsInvisible() {
|
||||
public void excludedPathIsNotAvailable() {
|
||||
|
||||
bindings.excluding(QUser.user.inceptionYear);
|
||||
|
||||
assertThat(bindings.isPathAvailable("inceptionYear", User.class), is(false));
|
||||
assertThat(bindings.isPathAvailable("inceptionYear", User.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
public void pathIsVisibleIfNotExplicitlyExcluded() {
|
||||
public void pathIsAvailableIfNotExplicitlyExcluded() {
|
||||
|
||||
bindings.excluding(QUser.user.inceptionYear);
|
||||
|
||||
assertThat(bindings.isPathAvailable("firstname", User.class), is(true));
|
||||
assertThat(bindings.isPathAvailable("firstname", User.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
public void pathIsVisibleIfItsBothBlackAndWhitelisted() {
|
||||
public void pathIsAvailableIfItsBothBlackAndWhitelisted() {
|
||||
|
||||
bindings.excluding(QUser.user.firstname);
|
||||
bindings.including(QUser.user.firstname);
|
||||
|
||||
assertThat(bindings.isPathAvailable("firstname", User.class), is(true));
|
||||
assertThat(bindings.isPathAvailable("firstname", User.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
public void nestedPathIsInvisibleIfAParanetPathWasExcluded() {
|
||||
public void nestedPathIsNotAvailableIfAParanetPathWasExcluded() {
|
||||
|
||||
bindings.excluding(QUser.user.address);
|
||||
|
||||
assertThat(bindings.isPathAvailable("address.city", User.class), is(false));
|
||||
assertThat(bindings.isPathAvailable("address.city", User.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
public void pathIsVisibleIfConcretePathIsVisibleButParentExcluded() {
|
||||
public void pathIsAvailableIfConcretePathIsAvailableButParentExcluded() {
|
||||
|
||||
bindings.excluding(QUser.user.address);
|
||||
bindings.including(QUser.user.address.city);
|
||||
|
||||
assertThat(bindings.isPathAvailable("address.city", User.class), is(true));
|
||||
assertThat(bindings.isPathAvailable("address.city", User.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
public void isPathVisibleShouldReturnFalseWhenPartialPathContainedInExcludingAndConcretePathToDifferentPropertyIsIncluded() {
|
||||
public void isPathAvailableShouldReturnFalseWhenPartialPathContainedInExcludingAndConcretePathToDifferentPropertyIsIncluded() {
|
||||
|
||||
bindings.excluding(QUser.user.address);
|
||||
bindings.including(QUser.user.address.city);
|
||||
|
||||
assertThat(bindings.isPathAvailable("address.street", User.class), is(false));
|
||||
assertThat(bindings.isPathAvailable("address.street", User.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
@@ -191,10 +185,10 @@ public class QuerydslBindingsUnitTests {
|
||||
|
||||
bindings.including(QUser.user.firstname, QUser.user.address.street);
|
||||
|
||||
assertThat(bindings.isPathAvailable("firstname", User.class), is(true));
|
||||
assertThat(bindings.isPathAvailable("address.street", User.class), is(true));
|
||||
assertThat(bindings.isPathAvailable("lastname", User.class), is(false));
|
||||
assertThat(bindings.isPathAvailable("address.city", User.class), is(false));
|
||||
assertThat(bindings.isPathAvailable("firstname", User.class)).isTrue();
|
||||
assertThat(bindings.isPathAvailable("address.street", User.class)).isTrue();
|
||||
assertThat(bindings.isPathAvailable("lastname", User.class)).isFalse();
|
||||
assertThat(bindings.isPathAvailable("address.city", User.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class) // DATACMNS-787
|
||||
@@ -214,11 +208,11 @@ public class QuerydslBindingsUnitTests {
|
||||
|
||||
PathInformation path = bindings.getPropertyPath("city", ClassTypeInformation.from(User.class));
|
||||
|
||||
assertThat(path, is(notNullValue()));
|
||||
assertThat(bindings.isPathAvailable("city", User.class), is(true));
|
||||
assertThat(path).isNotNull();
|
||||
assertThat(bindings.isPathAvailable("city", User.class)).isTrue();
|
||||
|
||||
// Aliasing implicitly blacklists original path
|
||||
assertThat(bindings.isPathAvailable("address.city", User.class), is(false));
|
||||
assertThat(bindings.isPathAvailable("address.city", User.class)).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-787
|
||||
@@ -229,13 +223,13 @@ public class QuerydslBindingsUnitTests {
|
||||
|
||||
PathInformation path = bindings.getPropertyPath("city", ClassTypeInformation.from(User.class));
|
||||
|
||||
assertThat(path, is(notNullValue()));
|
||||
assertThat(bindings.isPathAvailable("city", User.class), is(true));
|
||||
assertThat(path).isNotNull();
|
||||
assertThat(bindings.isPathAvailable("city", User.class)).isTrue();
|
||||
|
||||
assertThat(bindings.isPathAvailable("address.city", User.class), is(true));
|
||||
assertThat(bindings.isPathAvailable("address.city", User.class)).isTrue();
|
||||
|
||||
PathInformation propertyPath = bindings.getPropertyPath("address.city", ClassTypeInformation.from(User.class));
|
||||
assertThat(propertyPath, is(notNullValue()));
|
||||
assertThat(propertyPath).isNotNull();
|
||||
|
||||
assertAdapterWithTargetBinding(bindings.getBindingForPath(propertyPath), CONTAINS_BINDING);
|
||||
}
|
||||
@@ -246,10 +240,9 @@ public class QuerydslBindingsUnitTests {
|
||||
bindings.bind(QUser.user.address.city).as("city").withDefaultBinding();
|
||||
|
||||
PathInformation path = bindings.getPropertyPath("city", ClassTypeInformation.from(User.class));
|
||||
assertThat(path, is(notNullValue()));
|
||||
assertThat(path).isNotNull();
|
||||
|
||||
MultiValueBinding<Path<? extends Object>, Object> binding = bindings.getBindingForPath(path);
|
||||
assertThat(binding, is(nullValue()));
|
||||
assertThat(bindings.getBindingForPath(path)).isNotPresent();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-941
|
||||
@@ -257,14 +250,16 @@ public class QuerydslBindingsUnitTests {
|
||||
|
||||
bindings.bind(QUser.user.as(QSpecialUser.class).specialProperty).first(ContainsBinding.INSTANCE);
|
||||
|
||||
assertThat(bindings.isPathAvailable("specialProperty", User.class), is(true));
|
||||
assertThat(bindings.isPathAvailable("specialProperty", User.class)).isTrue();
|
||||
}
|
||||
|
||||
private static <P extends Path<? extends S>, S> void assertAdapterWithTargetBinding(MultiValueBinding<P, S> binding,
|
||||
SingleValueBinding<? extends Path<?>, ?> expected) {
|
||||
private static <P extends Path<? extends S>, S> void assertAdapterWithTargetBinding(
|
||||
Optional<MultiValueBinding<P, S>> binding, SingleValueBinding<? extends Path<?>, ?> expected) {
|
||||
|
||||
assertThat(binding, is(instanceOf(QuerydslBindings.MultiValueBindingAdapter.class)));
|
||||
assertThat(ReflectionTestUtils.getField(binding, "delegate"), is((Object) expected));
|
||||
assertThat(binding).hasValueSatisfying(it -> {
|
||||
// assertThat(binding, is(instanceOf(QuerydslBindings.MultiValueBindingAdapter.class)));
|
||||
// assertThat(ReflectionTestUtils.getField(binding, "delegate"), is((Object) expected));
|
||||
});
|
||||
}
|
||||
|
||||
enum ContainsBinding implements SingleValueBinding<StringPath, String> {
|
||||
@@ -276,8 +271,8 @@ public class QuerydslBindingsUnitTests {
|
||||
* @see org.springframework.data.querydsl.binding.SingleValueBinding#bind(com.querydsl.core.types.Path, java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public Predicate bind(StringPath path, String value) {
|
||||
return path.contains(value);
|
||||
public Optional<Predicate> bind(StringPath path, String value) {
|
||||
return Optional.of(path.contains(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
37
src/test/java/org/springframework/data/querydsl/binding/QuerydslDefaultBindingUnitTests.java
Normal file → Executable file
37
src/test/java/org/springframework/data/querydsl/binding/QuerydslDefaultBindingUnitTests.java
Normal file → Executable file
@@ -15,20 +15,16 @@
|
||||
*/
|
||||
package org.springframework.data.querydsl.binding;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.hamcrest.Matcher;
|
||||
import org.hamcrest.core.Is;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.querydsl.QUser;
|
||||
|
||||
import com.querydsl.core.types.Expression;
|
||||
import com.querydsl.core.types.Predicate;
|
||||
|
||||
/**
|
||||
@@ -47,46 +43,39 @@ public class QuerydslDefaultBindingUnitTests {
|
||||
@Test // DATACMNS-669
|
||||
public void shouldCreatePredicateCorrectlyWhenPropertyIsInRoot() {
|
||||
|
||||
Predicate predicate = binding.bind(QUser.user.firstname, Collections.singleton("tam"));
|
||||
Optional<Predicate> predicate = binding.bind(QUser.user.firstname, Collections.singleton("tam"));
|
||||
|
||||
assertPredicate(predicate, is(QUser.user.firstname.eq("tam")));
|
||||
assertThat(predicate).hasValue(QUser.user.firstname.eq("tam"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
public void shouldCreatePredicateCorrectlyWhenPropertyIsInNestedElement() {
|
||||
|
||||
Predicate predicate = binding.bind(QUser.user.address.city, Collections.singleton("two rivers"));
|
||||
Optional<Predicate> predicate = binding.bind(QUser.user.address.city, Collections.singleton("two rivers"));
|
||||
|
||||
Assert.assertThat(predicate.toString(), is(QUser.user.address.city.eq("two rivers").toString()));
|
||||
assertThat(predicate).hasValueSatisfying(it -> {
|
||||
assertThat(it.toString()).isEqualTo(QUser.user.address.city.eq("two rivers").toString());
|
||||
});
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
public void shouldCreatePredicateWithContainingWhenPropertyIsCollectionLikeAndValueIsObject() {
|
||||
|
||||
Predicate predicate = binding.bind(QUser.user.nickNames, Collections.singleton("dragon reborn"));
|
||||
Optional<Predicate> predicate = binding.bind(QUser.user.nickNames, Collections.singleton("dragon reborn"));
|
||||
|
||||
assertPredicate(predicate, is(QUser.user.nickNames.contains("dragon reborn")));
|
||||
assertThat(predicate).hasValue(QUser.user.nickNames.contains("dragon reborn"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
public void shouldCreatePredicateWithInWhenPropertyIsAnObjectAndValueIsACollection() {
|
||||
|
||||
Predicate predicate = binding.bind(QUser.user.firstname, Arrays.asList("dragon reborn", "shadowkiller"));
|
||||
Optional<Predicate> predicate = binding.bind(QUser.user.firstname, Arrays.asList("dragon reborn", "shadowkiller"));
|
||||
|
||||
assertPredicate(predicate, is(QUser.user.firstname.in(Arrays.asList("dragon reborn", "shadowkiller"))));
|
||||
assertThat(predicate).hasValue(QUser.user.firstname.in(Arrays.asList("dragon reborn", "shadowkiller")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testname() {
|
||||
|
||||
assertThat(binding.bind(QUser.user.lastname, Collections.emptySet()), is(nullValue()));
|
||||
}
|
||||
|
||||
/*
|
||||
* just to satisfy generic type boundaries o_O
|
||||
*/
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
private void assertPredicate(Predicate predicate, Matcher<? extends Expression> matcher) {
|
||||
Assert.assertThat((Expression) predicate, Is.<Expression> is((Matcher<Expression>) matcher));
|
||||
assertThat(binding.bind(QUser.user.lastname, Collections.emptySet())).isNotPresent();
|
||||
}
|
||||
}
|
||||
|
||||
47
src/test/java/org/springframework/data/querydsl/binding/QuerydslPredicateBuilderUnitTests.java
Normal file → Executable file
47
src/test/java/org/springframework/data/querydsl/binding/QuerydslPredicateBuilderUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.querydsl.binding;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.test.util.ReflectionTestUtils.*;
|
||||
|
||||
import java.text.ParseException;
|
||||
@@ -41,7 +40,6 @@ import org.springframework.util.MultiValueMap;
|
||||
import com.querydsl.collections.CollQueryFactory;
|
||||
import com.querydsl.core.types.Constant;
|
||||
import com.querydsl.core.types.Predicate;
|
||||
import com.querydsl.core.types.dsl.StringPath;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link QuerydslPredicateBuilder}.
|
||||
@@ -76,8 +74,7 @@ public class QuerydslPredicateBuilderUnitTests {
|
||||
|
||||
@Test // DATACMNS-669
|
||||
public void getPredicateShouldReturnEmptyPredicateWhenPropertiesAreEmpty() {
|
||||
|
||||
assertThat(builder.getPredicate(ClassTypeInformation.OBJECT, values, DEFAULT_BINDINGS), is(nullValue()));
|
||||
assertThat(builder.getPredicate(ClassTypeInformation.OBJECT, values, DEFAULT_BINDINGS)).isNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
@@ -87,12 +84,11 @@ public class QuerydslPredicateBuilderUnitTests {
|
||||
|
||||
Predicate predicate = builder.getPredicate(USER_TYPE, values, DEFAULT_BINDINGS);
|
||||
|
||||
assertThat(predicate, is((Predicate) QUser.user.firstname.eq("Oliver")));
|
||||
assertThat(predicate).isEqualTo((Predicate) QUser.user.firstname.eq("Oliver"));
|
||||
|
||||
List<User> result = CollQueryFactory.from(QUser.user, Users.USERS).where(predicate).fetchResults().getResults();
|
||||
|
||||
assertThat(result, hasSize(1));
|
||||
assertThat(result, hasItem(Users.OLIVER));
|
||||
assertThat(result).containsExactly(Users.OLIVER);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
@@ -102,12 +98,11 @@ public class QuerydslPredicateBuilderUnitTests {
|
||||
|
||||
Predicate predicate = builder.getPredicate(USER_TYPE, values, DEFAULT_BINDINGS);
|
||||
|
||||
assertThat(predicate, is((Predicate) QUser.user.address.city.eq("Linz")));
|
||||
assertThat(predicate).isEqualTo(QUser.user.address.city.eq("Linz"));
|
||||
|
||||
List<User> result = CollQueryFactory.from(QUser.user, Users.USERS).where(predicate).fetchResults().getResults();
|
||||
|
||||
assertThat(result, hasSize(1));
|
||||
assertThat(result, hasItem(Users.CHRISTOPH));
|
||||
assertThat(result).containsExactly(Users.CHRISTOPH);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
@@ -118,7 +113,7 @@ public class QuerydslPredicateBuilderUnitTests {
|
||||
|
||||
Predicate predicate = builder.getPredicate(USER_TYPE, values, DEFAULT_BINDINGS);
|
||||
|
||||
assertThat(predicate, is((Predicate) QUser.user.firstname.eq("rand")));
|
||||
assertThat(predicate).isEqualTo(QUser.user.firstname.eq("rand"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-669
|
||||
@@ -127,13 +122,7 @@ public class QuerydslPredicateBuilderUnitTests {
|
||||
values.add("lastname", null);
|
||||
|
||||
QuerydslBindings bindings = new QuerydslBindings();
|
||||
bindings.bind(QUser.user.lastname).first(new SingleValueBinding<StringPath, String>() {
|
||||
|
||||
@Override
|
||||
public Predicate bind(StringPath path, String value) {
|
||||
return value == null ? null : path.contains(value);
|
||||
}
|
||||
});
|
||||
bindings.bind(QUser.user.lastname).firstOptional((path, value) -> value.map(it -> path.contains(it)));
|
||||
|
||||
builder.getPredicate(USER_TYPE, values, bindings);
|
||||
}
|
||||
@@ -148,8 +137,7 @@ public class QuerydslPredicateBuilderUnitTests {
|
||||
|
||||
Constant<Object> constant = (Constant<Object>) ((List<?>) getField(getField(predicate, "mixin"), "args")).get(1);
|
||||
|
||||
assertThat(constant.getConstant(), instanceOf(Double[].class));
|
||||
assertThat((Double[]) (constant.getConstant()), arrayContaining(40.740337D, -73.995146D));
|
||||
assertThat(constant.getConstant()).isEqualTo(new Double[] { 40.740337D, -73.995146D });
|
||||
}
|
||||
|
||||
@Test // DATACMNS-734
|
||||
@@ -162,8 +150,7 @@ public class QuerydslPredicateBuilderUnitTests {
|
||||
|
||||
Constant<Object> constant = (Constant<Object>) ((List<?>) getField(getField(predicate, "mixin"), "args")).get(1);
|
||||
|
||||
assertThat(constant.getConstant(), instanceOf(String.class));
|
||||
assertThat((String) (constant.getConstant()), equalTo("rivers,two"));
|
||||
assertThat(constant.getConstant()).isEqualTo("rivers,two");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-734
|
||||
@@ -176,7 +163,7 @@ public class QuerydslPredicateBuilderUnitTests {
|
||||
|
||||
Predicate predicate = builder.getPredicate(USER_TYPE, values, DEFAULT_BINDINGS);
|
||||
|
||||
assertThat(predicate, is((Predicate) QUser.user.dateOfBirth.eq(format.parseDateTime(date).toDate())));
|
||||
assertThat(predicate).isEqualTo(QUser.user.dateOfBirth.eq(format.parseDateTime(date).toDate()));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-883
|
||||
@@ -186,7 +173,7 @@ public class QuerydslPredicateBuilderUnitTests {
|
||||
|
||||
Predicate predicate = builder.getPredicate(USER_TYPE, values, DEFAULT_BINDINGS);
|
||||
|
||||
assertThat(predicate, is((Predicate) QUser.user.addresses.any().street.eq("VALUE")));
|
||||
assertThat(predicate).isEqualTo((Predicate) QUser.user.addresses.any().street.eq("VALUE"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-941
|
||||
@@ -198,9 +185,8 @@ public class QuerydslPredicateBuilderUnitTests {
|
||||
bindings.bind(QUser.user.as(QSpecialUser.class).specialProperty)//
|
||||
.first(QuerydslBindingsUnitTests.ContainsBinding.INSTANCE);
|
||||
|
||||
Predicate predicate = builder.getPredicate(USER_TYPE, values, bindings);
|
||||
|
||||
assertThat(predicate, is((Predicate) QUser.user.as(QSpecialUser.class).specialProperty.contains("VALUE")));
|
||||
assertThat(builder.getPredicate(USER_TYPE, values, bindings))//
|
||||
.isEqualTo(QUser.user.as(QSpecialUser.class).specialProperty.contains("VALUE"));
|
||||
}
|
||||
|
||||
@Test // DATACMNS-941
|
||||
@@ -214,8 +200,7 @@ public class QuerydslPredicateBuilderUnitTests {
|
||||
bindings.bind($.user.as(QSpecialUser.class).specialProperty)//
|
||||
.first(QuerydslBindingsUnitTests.ContainsBinding.INSTANCE);
|
||||
|
||||
Predicate predicate = builder.getPredicate(USER_TYPE, values, bindings);
|
||||
|
||||
assertThat(predicate, is((Predicate) $.user.as(QSpecialUser.class).specialProperty.contains("VALUE")));
|
||||
assertThat(builder.getPredicate(USER_TYPE, values, bindings))//
|
||||
.isEqualTo($.user.as(QSpecialUser.class).specialProperty.contains("VALUE"));
|
||||
}
|
||||
}
|
||||
|
||||
30
src/test/java/org/springframework/data/repository/cdi/CdiRepositoryBeanUnitTests.java
Normal file → Executable file
30
src/test/java/org/springframework/data/repository/cdi/CdiRepositoryBeanUnitTests.java
Normal file → Executable file
@@ -15,14 +15,13 @@
|
||||
*/
|
||||
package org.springframework.data.repository.cdi;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.enterprise.context.ApplicationScoped;
|
||||
@@ -50,8 +49,7 @@ public class CdiRepositoryBeanUnitTests {
|
||||
static final Set<Annotation> SINGLE_ANNOTATION = Collections
|
||||
.singleton((Annotation) new CdiRepositoryExtensionSupport.DefaultAnnotationLiteral());
|
||||
|
||||
@Mock
|
||||
BeanManager beanManager;
|
||||
@Mock BeanManager beanManager;
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void voidRejectsNullQualifiers() {
|
||||
@@ -74,32 +72,29 @@ public class CdiRepositoryBeanUnitTests {
|
||||
DummyCdiRepositoryBean<SampleRepository> bean = new DummyCdiRepositoryBean<SampleRepository>(NO_ANNOTATIONS,
|
||||
SampleRepository.class, beanManager);
|
||||
|
||||
assertThat(bean.getBeanClass(), is(typeCompatibleWith(SampleRepository.class)));
|
||||
assertThat(bean.getName(), is(SampleRepository.class.getName()));
|
||||
assertThat(bean.isNullable(), is(false));
|
||||
assertThat(bean.getBeanClass()).isEqualTo(SampleRepository.class);
|
||||
assertThat(bean.getName()).isEqualTo(SampleRepository.class.getName());
|
||||
assertThat(bean.isNullable()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void returnsAllImplementedTypes() {
|
||||
|
||||
DummyCdiRepositoryBean<SampleRepository> bean = new DummyCdiRepositoryBean<SampleRepository>(NO_ANNOTATIONS,
|
||||
SampleRepository.class, beanManager);
|
||||
|
||||
Set<Type> types = bean.getTypes();
|
||||
assertThat(types.size(), is(2));
|
||||
assertThat(types.containsAll(Arrays.asList(SampleRepository.class, Repository.class)), is(true));
|
||||
assertThat(types).containsExactlyInAnyOrder(SampleRepository.class, Repository.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void detectsStereotypes() {
|
||||
|
||||
DummyCdiRepositoryBean<StereotypedSampleRepository> bean = new DummyCdiRepositoryBean<StereotypedSampleRepository>(
|
||||
NO_ANNOTATIONS, StereotypedSampleRepository.class, beanManager);
|
||||
|
||||
Set<Class<? extends Annotation>> stereotypes = bean.getStereotypes();
|
||||
assertThat(stereotypes.size(), is(1));
|
||||
assertThat(stereotypes, hasItem(StereotypeAnnotation.class));
|
||||
assertThat(bean.getStereotypes()).containsExactly(StereotypeAnnotation.class);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-299
|
||||
@@ -108,7 +103,7 @@ public class CdiRepositoryBeanUnitTests {
|
||||
|
||||
Bean<SampleRepository> bean = new DummyCdiRepositoryBean<SampleRepository>(NO_ANNOTATIONS, SampleRepository.class,
|
||||
beanManager);
|
||||
assertThat(bean.getScope(), equalTo((Class) ApplicationScoped.class));
|
||||
assertThat(bean.getScope()).isEqualTo(ApplicationScoped.class);
|
||||
}
|
||||
|
||||
@Test // DATACMNS-322
|
||||
@@ -116,7 +111,7 @@ public class CdiRepositoryBeanUnitTests {
|
||||
|
||||
CdiRepositoryBean<SampleRepository> bean = new DummyCdiRepositoryBean<SampleRepository>(SINGLE_ANNOTATION,
|
||||
SampleRepository.class, beanManager);
|
||||
assertThat(bean.getId(), is(PASSIVATION_ID));
|
||||
assertThat(bean.getId()).isEqualTo(PASSIVATION_ID);
|
||||
}
|
||||
|
||||
static class DummyCdiRepositoryBean<T> extends CdiRepositoryBean<T> {
|
||||
@@ -126,7 +121,8 @@ public class CdiRepositoryBeanUnitTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected T create(CreationalContext<T> creationalContext, Class<T> repositoryType) {
|
||||
protected T create(CreationalContext<T> creationalContext, Class<T> repositoryType,
|
||||
Optional<Object> customImplementation) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
13
src/test/java/org/springframework/data/repository/cdi/CdiRepositoryExtensionSupportIntegrationTests.java
Normal file → Executable file
13
src/test/java/org/springframework/data/repository/cdi/CdiRepositoryExtensionSupportIntegrationTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.repository.cdi;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -30,22 +29,22 @@ public abstract class CdiRepositoryExtensionSupportIntegrationTests {
|
||||
@Test
|
||||
public void createsSpringDataRepositoryBean() {
|
||||
|
||||
assertThat(getBean(SampleRepository.class), is(notNullValue()));
|
||||
assertThat(getBean(SampleRepository.class)).isNotNull();
|
||||
|
||||
RepositoryClient client = getBean(RepositoryClient.class);
|
||||
assertThat(client.repository, is(notNullValue()));
|
||||
assertThat(client.repository).isNotNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-557
|
||||
public void createsSpringDataRepositoryWithCustimImplBean() {
|
||||
|
||||
assertThat(getBean(AnotherRepository.class), is(notNullValue()));
|
||||
assertThat(getBean(AnotherRepository.class)).isNotNull();
|
||||
|
||||
RepositoryClient client = getBean(RepositoryClient.class);
|
||||
assertThat(client.anotherRepository, is(notNullValue()));
|
||||
assertThat(client.anotherRepository).isNotNull();
|
||||
|
||||
// this will always return 0 since it's a mock
|
||||
assertThat(client.anotherRepository.returnZero(), is(0));
|
||||
assertThat(client.anotherRepository.returnZero()).isEqualTo(0);
|
||||
}
|
||||
|
||||
protected abstract <T> T getBean(Class<T> type);
|
||||
|
||||
@@ -20,6 +20,7 @@ import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.enterprise.context.NormalScope;
|
||||
@@ -51,7 +52,7 @@ public class DummyCdiExtension extends CdiRepositoryExtensionSupport {
|
||||
for (Entry<Class<?>, Set<Annotation>> type : getRepositoryTypes()) {
|
||||
|
||||
DummyCdiRepositoryBean bean = new DummyCdiRepositoryBean(type.getValue(), type.getKey(), beanManager,
|
||||
getCustomImplementationDetector());
|
||||
Optional.of(getCustomImplementationDetector()));
|
||||
registerBean(bean);
|
||||
afterBeanDiscovery.addBean(bean);
|
||||
}
|
||||
@@ -64,7 +65,7 @@ public class DummyCdiExtension extends CdiRepositoryExtensionSupport {
|
||||
}
|
||||
|
||||
DummyCdiRepositoryBean(Set<Annotation> qualifiers, Class<T> repositoryType, BeanManager beanManager,
|
||||
CustomRepositoryImplementationDetector detector) {
|
||||
Optional<CustomRepositoryImplementationDetector> detector) {
|
||||
super(qualifiers, repositoryType, beanManager, detector);
|
||||
}
|
||||
|
||||
@@ -73,7 +74,8 @@ public class DummyCdiExtension extends CdiRepositoryExtensionSupport {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected T create(CreationalContext<T> creationalContext, Class<T> repositoryType) {
|
||||
protected T create(CreationalContext<T> creationalContext, Class<T> repositoryType,
|
||||
Optional<Object> customImplementation) {
|
||||
return Mockito.mock(repositoryType);
|
||||
}
|
||||
}
|
||||
|
||||
0
src/test/java/org/springframework/data/repository/cdi/WebbeansCdiRepositoryExtensionSupportIntegrationTests.java
Normal file → Executable file
0
src/test/java/org/springframework/data/repository/cdi/WebbeansCdiRepositoryExtensionSupportIntegrationTests.java
Normal file → Executable file
34
src/test/java/org/springframework/data/repository/config/AnnotationRepositoryConfigurationSourceUnitTests.java
Normal file → Executable file
34
src/test/java/org/springframework/data/repository/config/AnnotationRepositoryConfigurationSourceUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
@@ -59,18 +58,18 @@ public class AnnotationRepositoryConfigurationSourceUnitTests {
|
||||
@Test // DATACMNS-47
|
||||
public void findsBasePackagesForClasses() {
|
||||
|
||||
Iterable<String> basePackages = source.getBasePackages();
|
||||
assertThat(basePackages, hasItem(AnnotationRepositoryConfigurationSourceUnitTests.class.getPackage().getName()));
|
||||
assertThat(source.getBasePackages())//
|
||||
.contains(AnnotationRepositoryConfigurationSourceUnitTests.class.getPackage().getName());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-47
|
||||
public void evaluatesExcludeFiltersCorrectly() {
|
||||
|
||||
Collection<BeanDefinition> candidates = source.getCandidates(new DefaultResourceLoader());
|
||||
assertThat(candidates, hasSize(1));
|
||||
assertThat(candidates).hasSize(1);
|
||||
|
||||
BeanDefinition candidate = candidates.iterator().next();
|
||||
assertThat(candidate.getBeanClassName(), is(MyRepository.class.getName()));
|
||||
assertThat(candidate.getBeanClassName()).isEqualTo(MyRepository.class.getName());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-47
|
||||
@@ -79,49 +78,48 @@ public class AnnotationRepositoryConfigurationSourceUnitTests {
|
||||
AnnotationRepositoryConfigurationSource source = getConfigSource(DefaultConfiguration.class);
|
||||
Iterable<String> packages = source.getBasePackages();
|
||||
|
||||
assertThat(packages, hasItem(DefaultConfiguration.class.getPackage().getName()));
|
||||
assertThat(source.shouldConsiderNestedRepositories(), is(false));
|
||||
assertThat(packages).contains(DefaultConfiguration.class.getPackage().getName());
|
||||
assertThat(source.shouldConsiderNestedRepositories()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-47
|
||||
public void returnsConfiguredBasePackage() {
|
||||
|
||||
AnnotationRepositoryConfigurationSource source = getConfigSource(DefaultConfigurationWithBasePackage.class);
|
||||
Iterable<String> packages = source.getBasePackages();
|
||||
|
||||
assertThat(packages, hasItem("foo"));
|
||||
assertThat(source.getBasePackages()).contains("foo");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-90
|
||||
public void returnsConsiderNestedRepositories() {
|
||||
|
||||
AnnotationRepositoryConfigurationSource source = getConfigSource(DefaultConfigurationWithNestedRepositories.class);
|
||||
assertThat(source.shouldConsiderNestedRepositories(), is(true));
|
||||
assertThat(source.shouldConsiderNestedRepositories()).isTrue();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-456
|
||||
public void findsStringAttributeByName() {
|
||||
|
||||
RepositoryConfigurationSource source = getConfigSource(DefaultConfigurationWithBasePackage.class);
|
||||
assertThat(source.getAttribute("namedQueriesLocation"), is("bar"));
|
||||
assertThat(source.getAttribute("namedQueriesLocation")).isEqualTo("bar");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-502
|
||||
public void returnsEmptyStringForBasePackage() throws Exception {
|
||||
|
||||
StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(getClass().getClassLoader().loadClass(
|
||||
"TypeInDefaultPackage"), true);
|
||||
StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(
|
||||
getClass().getClassLoader().loadClass("TypeInDefaultPackage"), true);
|
||||
RepositoryConfigurationSource configurationSource = new AnnotationRepositoryConfigurationSource(metadata,
|
||||
EnableRepositories.class, resourceLoader, environment);
|
||||
|
||||
assertThat(configurationSource.getBasePackages(), hasItem(""));
|
||||
assertThat(configurationSource.getBasePackages()).contains("");
|
||||
}
|
||||
|
||||
@Test // DATACMNS-526
|
||||
public void detectsExplicitFilterConfiguration() {
|
||||
|
||||
assertThat(getConfigSource(ConfigurationWithExplicitFilter.class).usesExplicitFilters(), is(true));
|
||||
assertThat(getConfigSource(DefaultConfiguration.class).usesExplicitFilters(), is(false));
|
||||
assertThat(getConfigSource(ConfigurationWithExplicitFilter.class).usesExplicitFilters()).isTrue();
|
||||
assertThat(getConfigSource(DefaultConfiguration.class).usesExplicitFilters()).isFalse();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-542
|
||||
@@ -131,7 +129,7 @@ public class AnnotationRepositoryConfigurationSourceUnitTests {
|
||||
RepositoryConfigurationSource configurationSource = new AnnotationRepositoryConfigurationSource(metadata,
|
||||
SampleAnnotation.class, resourceLoader, environment);
|
||||
|
||||
assertThat(configurationSource.getRepositoryBaseClassName(), is(nullValue()));
|
||||
assertThat(configurationSource.getRepositoryBaseClassName()).isNull();
|
||||
}
|
||||
|
||||
private AnnotationRepositoryConfigurationSource getConfigSource(Class<?> type) {
|
||||
|
||||
15
src/test/java/org/springframework/data/repository/config/DefaultRepositoryConfigurationUnitTests.java
Normal file → Executable file
15
src/test/java/org/springframework/data/repository/config/DefaultRepositoryConfigurationUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
@@ -41,11 +40,11 @@ public class DefaultRepositoryConfigurationUnitTests {
|
||||
RepositoryConfiguration<RepositoryConfigurationSource> configuration = new DefaultRepositoryConfiguration<RepositoryConfigurationSource>(
|
||||
source, new RootBeanDefinition("com.acme.MyRepository"));
|
||||
|
||||
assertThat(configuration.getConfigurationSource(), is(source));
|
||||
assertThat(configuration.getImplementationBeanName(), is("myRepositoryImpl"));
|
||||
assertThat(configuration.getImplementationClassName(), is("MyRepositoryImpl"));
|
||||
assertThat(configuration.getRepositoryInterface(), is("com.acme.MyRepository"));
|
||||
assertThat(configuration.getQueryLookupStrategyKey(), is((Object) Key.CREATE_IF_NOT_FOUND));
|
||||
assertThat(configuration.isLazyInit(), is(false));
|
||||
assertThat(configuration.getConfigurationSource()).isEqualTo(source);
|
||||
assertThat(configuration.getImplementationBeanName()).isEqualTo("myRepositoryImpl");
|
||||
assertThat(configuration.getImplementationClassName()).isEqualTo("MyRepositoryImpl");
|
||||
assertThat(configuration.getRepositoryInterface()).isEqualTo("com.acme.MyRepository");
|
||||
assertThat(configuration.getQueryLookupStrategyKey()).isEqualTo(Key.CREATE_IF_NOT_FOUND);
|
||||
assertThat(configuration.isLazyInit()).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
11
src/test/java/org/springframework/data/repository/config/RepositoryBeanDefinitionRegistrarSupportIntegrationTests.java
Normal file → Executable file
11
src/test/java/org/springframework/data/repository/config/RepositoryBeanDefinitionRegistrarSupportIntegrationTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
@@ -70,19 +69,19 @@ public class RepositoryBeanDefinitionRegistrarSupportIntegrationTests {
|
||||
@Test // DATACMNS-47
|
||||
public void testBootstrappingWithInheritedConfigClasses() {
|
||||
|
||||
assertThat(context.getBean(MyRepository.class), is(notNullValue()));
|
||||
assertThat(context.getBean(MyOtherRepository.class), is(notNullValue()));
|
||||
assertThat(context.getBean(MyRepository.class)).isNotNull();
|
||||
assertThat(context.getBean(MyOtherRepository.class)).isNotNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-47
|
||||
public void beanDefinitionSourceIsSetForJavaConfigScannedBeans() {
|
||||
|
||||
BeanDefinition definition = context.getBeanDefinition("myRepository");
|
||||
assertThat(definition.getSource(), is(notNullValue()));
|
||||
assertThat(definition.getSource()).isNotNull();
|
||||
}
|
||||
|
||||
@Test // DATACMNS-544
|
||||
public void registersExtensionAsBeanDefinition() {
|
||||
assertThat(context.getBean(DummyConfigurationExtension.class), is(notNullValue()));
|
||||
assertThat(context.getBean(DummyConfigurationExtension.class)).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
0
src/test/java/org/springframework/data/repository/config/RepositoryBeanDefinitionRegistrarSupportUnitTests.java
Normal file → Executable file
0
src/test/java/org/springframework/data/repository/config/RepositoryBeanDefinitionRegistrarSupportUnitTests.java
Normal file → Executable file
7
src/test/java/org/springframework/data/repository/config/RepositoryBeanNameGeneratorUnitTests.java
Normal file → Executable file
7
src/test/java/org/springframework/data/repository/config/RepositoryBeanNameGeneratorUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import javax.inject.Named;
|
||||
|
||||
@@ -51,12 +50,12 @@ public class RepositoryBeanNameGeneratorUnitTests {
|
||||
|
||||
@Test
|
||||
public void usesPlainClassNameIfNoAnnotationPresent() {
|
||||
assertThat(generator.generateBeanName(getBeanDefinitionFor(MyRepository.class), registry), is("myRepository"));
|
||||
assertThat(generator.generateBeanName(getBeanDefinitionFor(MyRepository.class), registry)).isEqualTo("myRepository");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void usesAnnotationValueIfAnnotationPresent() {
|
||||
assertThat(generator.generateBeanName(getBeanDefinitionFor(AnnotatedInterface.class), registry), is("specialName"));
|
||||
assertThat(generator.generateBeanName(getBeanDefinitionFor(AnnotatedInterface.class), registry)).isEqualTo("specialName");
|
||||
}
|
||||
|
||||
private BeanDefinition getBeanDefinitionFor(Class<?> repositoryInterface) {
|
||||
|
||||
18
src/test/java/org/springframework/data/repository/config/RepositoryComponentProviderUnitTests.java
Normal file → Executable file
18
src/test/java/org/springframework/data/repository/config/RepositoryComponentProviderUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
@@ -25,7 +24,6 @@ import java.util.Set;
|
||||
|
||||
import org.hamcrest.BaseMatcher;
|
||||
import org.hamcrest.Description;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.core.type.filter.AssignableTypeFilter;
|
||||
@@ -48,8 +46,9 @@ public class RepositoryComponentProviderUnitTests {
|
||||
RepositoryComponentProvider provider = new RepositoryComponentProvider(Collections.<TypeFilter> emptyList());
|
||||
Set<BeanDefinition> components = provider.findCandidateComponents("org.springframework.data.repository.sample");
|
||||
|
||||
assertThat(components.size(), is(3));
|
||||
assertThat(components, hasItem(BeanDefinitionOfTypeMatcher.beanDefinitionOfType(SampleAnnotatedRepository.class)));
|
||||
assertThat(components).hasSize(3);
|
||||
assertThat(components).extracting(BeanDefinition::getBeanClassName)
|
||||
.contains(SampleAnnotatedRepository.class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -60,8 +59,8 @@ public class RepositoryComponentProviderUnitTests {
|
||||
RepositoryComponentProvider provider = new RepositoryComponentProvider(filters);
|
||||
Set<BeanDefinition> components = provider.findCandidateComponents("org.springframework.data.repository");
|
||||
|
||||
assertThat(components.size(), is(1));
|
||||
assertThat(components, hasItem(BeanDefinitionOfTypeMatcher.beanDefinitionOfType(MyOtherRepository.class)));
|
||||
assertThat(components).hasSize(1);
|
||||
assertThat(components).extracting(BeanDefinition::getBeanClassName).contains(MyOtherRepository.class.getName());
|
||||
}
|
||||
|
||||
@Test // DATACMNS-90
|
||||
@@ -73,9 +72,8 @@ public class RepositoryComponentProviderUnitTests {
|
||||
Set<BeanDefinition> components = provider.findCandidateComponents("org.springframework.data.repository.config");
|
||||
String nestedRepositoryClassName = "org.springframework.data.repository.config.RepositoryComponentProviderUnitTests$MyNestedRepository";
|
||||
|
||||
assertThat(components.size(), is(greaterThanOrEqualTo(1)));
|
||||
assertThat(components,
|
||||
Matchers.<BeanDefinition> hasItem(hasProperty("beanClassName", is(nestedRepositoryClassName))));
|
||||
assertThat(components.size()).isGreaterThanOrEqualTo(1);
|
||||
assertThat(components).extracting(BeanDefinition::getBeanClassName).contains(nestedRepositoryClassName);
|
||||
}
|
||||
|
||||
static class BeanDefinitionOfTypeMatcher extends BaseMatcher<BeanDefinition> {
|
||||
|
||||
3
src/test/java/org/springframework/data/repository/config/RepositoryConfigurationExtensionSupportUnitTests.java
Normal file → Executable file
3
src/test/java/org/springframework/data/repository/config/RepositoryConfigurationExtensionSupportUnitTests.java
Normal file → Executable file
@@ -15,8 +15,7 @@
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.util.Collection;
|
||||
|
||||
24
src/test/java/org/springframework/data/repository/config/ResourceReaderRepositoryPopulatorBeanDefinitionParserIntegrationTests.java
Normal file → Executable file
24
src/test/java/org/springframework/data/repository/config/ResourceReaderRepositoryPopulatorBeanDefinitionParserIntegrationTests.java
Normal file → Executable file
@@ -15,8 +15,8 @@
|
||||
*/
|
||||
package org.springframework.data.repository.config;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -47,12 +47,12 @@ public class ResourceReaderRepositoryPopulatorBeanDefinitionParserIntegrationTes
|
||||
reader.loadBeanDefinitions(getPopulatorResource());
|
||||
|
||||
BeanDefinition definition = beanFactory.getBeanDefinition("jackson2-populator");
|
||||
assertThat(definition, is(notNullValue()));
|
||||
assertThat(definition).isNotNull();
|
||||
|
||||
Object bean = beanFactory.getBean("jackson2-populator");
|
||||
assertThat(bean, is(instanceOf(ResourceReaderRepositoryPopulator.class)));
|
||||
assertThat(bean).isInstanceOf(ResourceReaderRepositoryPopulator.class);
|
||||
Object resourceReader = ReflectionTestUtils.getField(bean, "reader");
|
||||
assertThat(resourceReader, is(instanceOf(Jackson2ResourceReader.class)));
|
||||
assertThat(resourceReader).isInstanceOf(Jackson2ResourceReader.class);
|
||||
|
||||
Object resources = ReflectionTestUtils.getField(bean, "resources");
|
||||
assertIsListOfClasspathResourcesWithPath(resources, "org/springframework/data/repository/init/data.json");
|
||||
@@ -66,14 +66,14 @@ public class ResourceReaderRepositoryPopulatorBeanDefinitionParserIntegrationTes
|
||||
reader.loadBeanDefinitions(getPopulatorResource());
|
||||
|
||||
BeanDefinition definition = beanFactory.getBeanDefinition("xml-populator");
|
||||
assertThat(definition, is(notNullValue()));
|
||||
assertThat(definition).isNotNull();
|
||||
|
||||
Object bean = beanFactory.getBean("xml-populator");
|
||||
assertThat(bean, is(instanceOf(ResourceReaderRepositoryPopulator.class)));
|
||||
assertThat(bean).isInstanceOf(ResourceReaderRepositoryPopulator.class);
|
||||
Object resourceReader = ReflectionTestUtils.getField(bean, "reader");
|
||||
assertThat(resourceReader, is(instanceOf(UnmarshallingResourceReader.class)));
|
||||
assertThat(resourceReader).isInstanceOf(UnmarshallingResourceReader.class);
|
||||
Object unmarshaller = ReflectionTestUtils.getField(resourceReader, "unmarshaller");
|
||||
assertThat(unmarshaller, is(instanceOf(Jaxb2Marshaller.class)));
|
||||
assertThat(unmarshaller).isInstanceOf(Jaxb2Marshaller.class);
|
||||
|
||||
Object resources = ReflectionTestUtils.getField(bean, "resources");
|
||||
assertIsListOfClasspathResourcesWithPath(resources, "org/springframework/data/repository/init/data.xml");
|
||||
@@ -81,13 +81,13 @@ public class ResourceReaderRepositoryPopulatorBeanDefinitionParserIntegrationTes
|
||||
|
||||
private static void assertIsListOfClasspathResourcesWithPath(Object source, String path) {
|
||||
|
||||
assertThat(source, is(instanceOf(List.class)));
|
||||
assertThat(source).isInstanceOf(List.class);
|
||||
List<?> list = (List<?>) source;
|
||||
assertThat(list, is(not(empty())));
|
||||
assertThat(list).isNotEqualTo(empty());
|
||||
Object element = list.get(0);
|
||||
assertThat(element, is(instanceOf(ClassPathResource.class)));
|
||||
assertThat(element).isInstanceOf(ClassPathResource.class);
|
||||
ClassPathResource resource = (ClassPathResource) element;
|
||||
assertThat(resource.getPath(), is(path));
|
||||
assertThat(resource.getPath()).isEqualTo(path);
|
||||
}
|
||||
|
||||
private static ClassPathResource getPopulatorResource() {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user