DATAJPA-1571 - Replaced Hamcrest assertions with AssertJ.

The following were not straight forward:
* Testing classes for assignability is not straight forward possible in the direction required. Replaced with equality check.
* Jpa21UtilsTests used custom matcher which got replaced by a custom assertions.
* The mentioned assertions were in IsAttributeNode.
  The new version is in Jpa21UtilsTests.

Also replaced exception checks with idiomatic AssertJ usage when found.
This commit is contained in:
Jens Schauder
2019-07-11 15:43:26 +02:00
parent 876dc93816
commit 4b6735d5aa
69 changed files with 1051 additions and 1126 deletions

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.convert.threeten;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.springframework.data.jpa.support.EntityManagerTestUtils.*;
@@ -39,20 +38,12 @@ import org.springframework.transaction.annotation.Transactional;
* Integration tests for {@link Jsr310JpaConverters}.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
@ContextConfiguration
@Transactional
public class Jsr310JpaConvertersIntegrationTests extends AbstractAttributeConverterIntegrationTests {
@Configuration
static class Config extends InfrastructureConfig {
@Override
protected String getPackageName() {
return getClass().getPackage().getName();
}
}
@PersistenceContext EntityManager em;
@Test // DATAJPA-650
@@ -74,11 +65,20 @@ public class Jsr310JpaConvertersIntegrationTests extends AbstractAttributeConver
DateTimeSample result = em.find(DateTimeSample.class, sample.id);
assertThat(result, is(notNullValue()));
assertThat(result.instant, is(sample.instant));
assertThat(result.localDate, is(sample.localDate));
assertThat(result.localTime, is(sample.localTime));
assertThat(result.localDateTime, is(sample.localDateTime));
assertThat(result.zoneId, is(sample.zoneId));
assertThat(result).isNotNull();
assertThat(result.instant).isEqualTo(sample.instant);
assertThat(result.localDate).isEqualTo(sample.localDate);
assertThat(result.localTime).isEqualTo(sample.localTime);
assertThat(result.localDateTime).isEqualTo(sample.localDateTime);
assertThat(result.zoneId).isEqualTo(sample.zoneId);
}
@Configuration
static class Config extends InfrastructureConfig {
@Override
protected String getPackageName() {
return getClass().getPackage().getName();
}
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.convert.threetenbp;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.springframework.data.jpa.support.EntityManagerTestUtils.*;
@@ -38,21 +37,13 @@ import org.threeten.bp.ZoneId;
* Integration tests for {@link ThreeTenBackPortJpaConverters}.
*
* @author Oliver Gierke
* @author Jens Schauder
* @since 1.8
*/
@ContextConfiguration
@Transactional
public class ThreeTenBackPortJpaConvertersIntegrationTests extends AbstractAttributeConverterIntegrationTests {
@Configuration
static class Config extends InfrastructureConfig {
@Override
protected String getPackageName() {
return getClass().getPackage().getName();
}
}
@PersistenceContext EntityManager em;
@Test // DATAJPA-650
@@ -74,11 +65,20 @@ public class ThreeTenBackPortJpaConvertersIntegrationTests extends AbstractAttri
DateTimeSample result = em.find(DateTimeSample.class, sample.id);
assertThat(result, is(notNullValue()));
assertThat(result.instant, is(sample.instant));
assertThat(result.localDate, is(sample.localDate));
assertThat(result.localTime, is(sample.localTime));
assertThat(result.localDateTime, is(sample.localDateTime));
assertThat(result.zoneId, is(sample.zoneId));
assertThat(result).isNotNull();
assertThat(result.instant).isEqualTo(sample.instant);
assertThat(result.localDate).isEqualTo(sample.localDate);
assertThat(result.localTime).isEqualTo(sample.localTime);
assertThat(result.localDateTime).isEqualTo(sample.localDateTime);
assertThat(result.zoneId).isEqualTo(sample.zoneId);
}
@Configuration
static class Config extends InfrastructureConfig {
@Override
protected String getPackageName() {
return getClass().getPackage().getName();
}
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.domain;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.domain.Sort.Direction.*;
import static org.springframework.data.jpa.domain.JpaSort.*;
@@ -29,8 +28,7 @@ import org.junit.runner.RunWith;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.JpaSort.JpaOrder;
import org.springframework.data.jpa.domain.JpaSort.Path;
import org.springframework.data.jpa.domain.JpaSort.*;
import org.springframework.data.jpa.domain.sample.Address_;
import org.springframework.data.jpa.domain.sample.MailMessage_;
import org.springframework.data.jpa.domain.sample.MailSender_;
@@ -48,6 +46,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @author Thomas Darimont
* @author Oliver Gierke
* @author Christoph Strobl
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:infrastructure.xml")
@@ -81,66 +80,65 @@ public class JpaSortTests {
@Test // DATAJPA-12
public void sortBySinglePropertyWithDefaultSortDirection() {
assertThat(new JpaSort(path(User_.firstname)), hasItems(new Sort.Order("firstname")));
assertThat(new JpaSort(path(User_.firstname))).contains(new Sort.Order("firstname"));
}
@Test // DATAJPA-12
public void sortByMultiplePropertiesWithDefaultSortDirection() {
assertThat(new JpaSort(User_.firstname, User_.lastname), hasItems(new Order("firstname"), new Order("lastname")));
assertThat(new JpaSort(User_.firstname, User_.lastname)).contains(new Order("firstname"), new Order("lastname"));
}
@Test // DATAJPA-12
public void sortByMultiplePropertiesWithDescSortDirection() {
assertThat(new JpaSort(DESC, User_.firstname, User_.lastname),
hasItems(new Order(DESC, "firstname"), new Order(Direction.DESC, "lastname")));
assertThat(new JpaSort(DESC, User_.firstname, User_.lastname)).contains(new Order(DESC, "firstname"),
new Order(Direction.DESC, "lastname"));
}
@Test // DATAJPA-12
public void combiningSortByMultipleProperties() {
assertThat(new JpaSort(User_.firstname).and(new JpaSort(User_.lastname)),
hasItems(new Order("firstname"), new Order("lastname")));
assertThat(new JpaSort(User_.firstname).and(new JpaSort(User_.lastname))).contains(new Order("firstname"),
new Order("lastname"));
}
@Test // DATAJPA-12
public void combiningSortByMultiplePropertiesWithDifferentSort() {
assertThat(new JpaSort(User_.firstname).and(new JpaSort(DESC, User_.lastname)),
hasItems(new Order("firstname"), new Order(DESC, "lastname")));
assertThat(new JpaSort(User_.firstname).and(new JpaSort(DESC, User_.lastname))).contains(new Order("firstname"),
new Order(DESC, "lastname"));
}
@Test // DATAJPA-12
public void combiningSortByNestedEmbeddedProperty() {
assertThat(new JpaSort(path(User_.address).dot(Address_.streetName)), hasItems(new Order("address.streetName")));
assertThat(new JpaSort(path(User_.address).dot(Address_.streetName))).contains(new Order("address.streetName"));
}
@Test // DATAJPA-12
public void buildJpaSortFromJpaMetaModelSingleAttribute() {
assertThat(new JpaSort(ASC, path(User_.firstname)), //
hasItems(new Order("firstname")));
assertThat(new JpaSort(ASC, path(User_.firstname))).contains(new Order("firstname"));
}
@Test // DATAJPA-12
public void buildJpaSortFromJpaMetaModelNestedAttribute() {
assertThat(new JpaSort(ASC, path(MailMessage_.mailSender).dot(MailSender_.name)), //
hasItems(new Order("mailSender.name")));
assertThat(new JpaSort(ASC, path(MailMessage_.mailSender).dot(MailSender_.name)))
.contains(new Order("mailSender.name"));
}
@Test // DATAJPA-702
public void combiningSortByMultiplePropertiesWithDifferentSortUsingSimpleAnd() {
assertThat(new JpaSort(User_.firstname).and(DESC, User_.lastname),
contains(new Order("firstname"), new Order(DESC, "lastname")));
assertThat(new JpaSort(User_.firstname).and(DESC, User_.lastname)).containsExactly(new Order("firstname"),
new Order(DESC, "lastname"));
}
@Test // DATAJPA-702
public void combiningSortByMultiplePathsWithDifferentSortUsingSimpleAnd() {
assertThat(new JpaSort(User_.firstname).and(DESC, path(MailMessage_.mailSender).dot(MailSender_.name)),
contains(new Order("firstname"), new Order(DESC, "mailSender.name")));
assertThat(new JpaSort(User_.firstname).and(DESC, path(MailMessage_.mailSender).dot(MailSender_.name)))
.containsExactly(new Order("firstname"), new Order(DESC, "mailSender.name"));
}
@Test(expected = IllegalArgumentException.class) // DATAJPA-702
@@ -165,8 +163,8 @@ public class JpaSortTests {
JpaSort sort = JpaSort.unsafe(DESC, "foo.bar");
assertThat(sort, hasItem(new Order(DESC, "foo.bar")));
assertThat(sort.getOrderFor("foo.bar"), is(instanceOf(JpaOrder.class)));
assertThat(sort).contains(new Order(DESC, "foo.bar"));
assertThat(sort.getOrderFor("foo.bar")).isInstanceOf(JpaOrder.class);
}
@Test // DATAJPA-965
@@ -174,9 +172,9 @@ public class JpaSortTests {
JpaSort sort = JpaSort.unsafe(DESC, "foo.bar", "spring.data");
assertThat(sort, hasItems(new Order(DESC, "foo.bar"), new Order(DESC, "spring.data")));
assertThat(sort.getOrderFor("foo.bar"), is(instanceOf(JpaOrder.class)));
assertThat(sort.getOrderFor("spring.data"), is(instanceOf(JpaOrder.class)));
assertThat(sort).contains(new Order(DESC, "foo.bar"), new Order(DESC, "spring.data"));
assertThat(sort.getOrderFor("foo.bar")).isInstanceOf(JpaOrder.class);
assertThat(sort.getOrderFor("spring.data")).isInstanceOf(JpaOrder.class);
}
@Test // DATAJPA-965

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.domain;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.jpa.domain.Specification.*;
import static org.springframework.data.jpa.domain.Specification.not;
import static org.springframework.util.SerializationUtils.*;
@@ -40,6 +39,7 @@ import org.mockito.junit.MockitoJUnitRunner;
* @author Oliver Gierke
* @author Thomas Darimont
* @author Sebastian Staudt
* @author Jens Schauder
*/
@SuppressWarnings("serial")
@RunWith(MockitoJUnitRunner.class)
@@ -62,8 +62,8 @@ public class SpecificationUnitTests implements Serializable {
public void createsSpecificationsFromNull() {
Specification<Object> specification = where(null);
assertThat(specification, is(notNullValue()));
assertThat(specification.toPredicate(root, query, builder), is(nullValue()));
assertThat(specification).isNotNull();
assertThat(specification.toPredicate(root, query, builder)).isNull();
}
@Test // DATAJPA-300, DATAJPA-1170
@@ -71,8 +71,8 @@ public class SpecificationUnitTests implements Serializable {
Specification<Object> specification = not(null);
assertThat(specification, is(notNullValue()));
assertThat(specification.toPredicate(root, query, builder), is(nullValue()));
assertThat(specification).isNotNull();
assertThat(specification.toPredicate(root, query, builder)).isNull();
}
@Test // DATAJPA-300, DATAJPA-1170
@@ -81,8 +81,8 @@ public class SpecificationUnitTests implements Serializable {
Specification<Object> specification = where(null);
specification = specification.and(spec);
assertThat(specification, is(notNullValue()));
assertThat(specification.toPredicate(root, query, builder), is(predicate));
assertThat(specification).isNotNull();
assertThat(specification.toPredicate(root, query, builder)).isEqualTo(predicate);
}
@Test // DATAJPA-300, DATAJPA-1170
@@ -90,8 +90,8 @@ public class SpecificationUnitTests implements Serializable {
Specification<Object> specification = spec.and(null);
assertThat(specification, is(notNullValue()));
assertThat(specification.toPredicate(root, query, builder), is(predicate));
assertThat(specification).isNotNull();
assertThat(specification.toPredicate(root, query, builder)).isEqualTo(predicate);
}
@Test // DATAJPA-300, DATAJPA-1170
@@ -100,8 +100,8 @@ public class SpecificationUnitTests implements Serializable {
Specification<Object> specification = where(null);
specification = specification.or(spec);
assertThat(specification, is(notNullValue()));
assertThat(specification.toPredicate(root, query, builder), is(predicate));
assertThat(specification).isNotNull();
assertThat(specification.toPredicate(root, query, builder)).isEqualTo(predicate);
}
@Test // DATAJPA-300, DATAJPA-1170
@@ -109,8 +109,8 @@ public class SpecificationUnitTests implements Serializable {
Specification<Object> specification = spec.or(null);
assertThat(specification, is(notNullValue()));
assertThat(specification.toPredicate(root, query, builder), is(predicate));
assertThat(specification).isNotNull();
assertThat(specification.toPredicate(root, query, builder)).isEqualTo(predicate);
}
@Test // DATAJPA-523
@@ -119,12 +119,12 @@ public class SpecificationUnitTests implements Serializable {
Specification<Object> serializableSpec = new SerializableSpecification();
Specification<Object> specification = serializableSpec.and(serializableSpec);
assertThat(specification, is(notNullValue()));
assertThat(specification).isNotNull();
@SuppressWarnings("unchecked")
Specification<Object> transferredSpecification = (Specification<Object>) deserialize(serialize(specification));
assertThat(transferredSpecification, is(notNullValue()));
assertThat(transferredSpecification).isNotNull();
}
@Test // DATAJPA-523
@@ -134,12 +134,12 @@ public class SpecificationUnitTests implements Serializable {
Specification<Object> specification = Specification
.not(serializableSpec.and(serializableSpec).or(serializableSpec));
assertThat(specification, is(notNullValue()));
assertThat(specification).isNotNull();
@SuppressWarnings("unchecked")
Specification<Object> transferredSpecification = (Specification<Object>) deserialize(serialize(specification));
assertThat(transferredSpecification, is(notNullValue()));
assertThat(transferredSpecification).isNotNull();
}
public class SerializableSpecification implements Serializable, Specification<Object> {

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.domain.support;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import javax.persistence.EntityManagerFactory;
@@ -32,6 +31,7 @@ import org.springframework.core.io.ClassPathResource;
*
* @author Oliver Gierke
* @author Thomas Darimont
* @author Jens Schauder
*/
public class AuditingBeanFactoryPostProcessorUnitTests {
@@ -63,7 +63,7 @@ public class AuditingBeanFactoryPostProcessorUnitTests {
processor.postProcessBeanFactory(beanFactory);
assertThat(beanFactory.isBeanNameInUse(AuditingBeanFactoryPostProcessor.BEAN_CONFIGURER_ASPECT_BEAN_NAME), is(true));
assertThat(beanFactory.isBeanNameInUse(AuditingBeanFactoryPostProcessor.BEAN_CONFIGURER_ASPECT_BEAN_NAME)).isTrue();
}
@Test(expected = IllegalStateException.class) // DATAJPA-265
@@ -80,9 +80,9 @@ public class AuditingBeanFactoryPostProcessorUnitTests {
for (String emfDefinitionName : emfDefinitionNames) {
BeanDefinition emfDefinition = beanFactory.getBeanDefinition(emfDefinitionName);
assertThat(emfDefinition, is(notNullValue()));
assertThat(emfDefinition.getDependsOn(),
is(arrayContaining(AuditingBeanFactoryPostProcessor.BEAN_CONFIGURER_ASPECT_BEAN_NAME)));
assertThat(emfDefinition).isNotNull();
assertThat(emfDefinition.getDependsOn())
.containsExactly(AuditingBeanFactoryPostProcessor.BEAN_CONFIGURER_ASPECT_BEAN_NAME);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.domain.support;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.time.LocalDateTime;
import java.util.Optional;
@@ -56,6 +55,18 @@ public class AuditingEntityListenerTests {
AuditableUser user;
private static void assertDatesSet(Auditable<?, ?, LocalDateTime> auditable) {
assertThat(auditable.getCreatedDate().isPresent()).isTrue();
assertThat(auditable.getLastModifiedDate().isPresent()).isTrue();
}
private static void assertUserIsAuditor(AuditableUser user, Auditable<AuditableUser, ?, LocalDateTime> auditable) {
assertThat(auditable.getCreatedBy()).isEqualTo(Optional.of(user));
assertThat(auditable.getLastModifiedBy()).isEqualTo(Optional.of(user));
}
@Before
public void setUp() {
@@ -80,7 +91,7 @@ public class AuditingEntityListenerTests {
user = repository.saveAndFlush(user);
assertThat(user.getCreatedDate().get().isBefore(user.getLastModifiedDate().get()), is(true));
assertThat(user.getCreatedDate().get().isBefore(user.getLastModifiedDate().get())).isTrue();
}
@Test
@@ -106,19 +117,7 @@ public class AuditingEntityListenerTests {
AnnotatedAuditableUser auditableUser = annotatedUserRepository.save(new AnnotatedAuditableUser());
assertThat(auditableUser.getCreateAt(), is(notNullValue()));
assertThat(auditableUser.getLastModifiedBy(), is(notNullValue()));
}
private static void assertDatesSet(Auditable<?, ?, LocalDateTime> auditable) {
assertThat(auditable.getCreatedDate().isPresent(), is(true));
assertThat(auditable.getLastModifiedDate().isPresent(), is(true));
}
private static void assertUserIsAuditor(AuditableUser user, Auditable<AuditableUser, ?, LocalDateTime> auditable) {
assertThat(auditable.getCreatedBy(), is(Optional.of(user)));
assertThat(auditable.getLastModifiedBy(), is(Optional.of(user)));
assertThat(auditableUser.getCreateAt()).isNotNull();
assertThat(auditableUser.getLastModifiedBy()).isNotNull();
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.domain.support;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.beans.PropertyValue;
@@ -26,6 +25,7 @@ import org.springframework.beans.factory.config.BeanDefinition;
* Unit test for the JPA {@code auditing} namespace element.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
public class AuditingNamespaceUnitTests extends AuditingBeanFactoryPostProcessorUnitTests {
@@ -43,6 +43,6 @@ public class AuditingNamespaceUnitTests extends AuditingBeanFactoryPostProcessor
BeanDefinition definition = beanFactory.getBeanDefinition(AuditingEntityListener.class.getName());
PropertyValue propertyValue = definition.getPropertyValues().getPropertyValue("auditingHandler");
assertThat(propertyValue, is(notNullValue()));
assertThat(propertyValue).isNotNull();
}
}

View File

@@ -15,9 +15,7 @@
*/
package org.springframework.data.jpa.infrastructure;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.Assertions.*;
import java.util.List;
@@ -45,6 +43,7 @@ import org.springframework.transaction.annotation.Transactional;
/**
* @author Oliver Gierke
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:infrastructure.xml" })
@@ -59,7 +58,7 @@ public abstract class MetamodelIntegrationTests {
ManagedType<User> type = metamodel.managedType(User.class);
Attribute<? super User, ?> attribute = type.getSingularAttribute("manager");
assertThat(attribute.isAssociation(), is(true));
assertThat(attribute.isAssociation()).isTrue();
}
@Test
@@ -71,7 +70,7 @@ public abstract class MetamodelIntegrationTests {
Root<User> root = query.from(User.class);
Path<Object> path = root.get("manager");
assertThat(path.getModel().getBindableType(), is(BindableType.ENTITY_TYPE));
assertThat(path.getModel().getBindableType()).isEqualTo(BindableType.ENTITY_TYPE);
}
@Test
@@ -79,7 +78,7 @@ public abstract class MetamodelIntegrationTests {
Query query = em.createNativeQuery("SELECT u from User u where u.lastname = ?1");
assertThat(query.getParameter(1), is(notNullValue()));
assertThat(query.getParameter(1)).isNotNull();
}
@Test
@@ -98,8 +97,8 @@ public abstract class MetamodelIntegrationTests {
List<Tuple> result = query.getResultList();
List<TupleElement<?>> elements = result.get(0).getElements();
assertThat(elements, hasSize(1));
assertThat(elements.get(0).getAlias(), is(nullValue()));
assertThat(elements).hasSize(1);
assertThat(elements.get(0).getAlias()).isNull();
}
@Test

View File

@@ -15,9 +15,7 @@
*/
package org.springframework.data.jpa.mapping;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.Assertions.*;
import java.util.Collections;
@@ -51,23 +49,14 @@ import org.springframework.transaction.support.TransactionTemplate;
*
* @author Oliver Gierke
* @author Thomas Darimont
* @author Jens Schauder
* @since 1.3
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class JpaMetamodelMappingContextIntegrationTests {
@Configuration
@ImportResource("classpath:infrastructure.xml")
@EnableJpaRepositories(basePackageClasses = CategoryRepository.class, //
includeFilters = @Filter(value = { CategoryRepository.class, ProductRepository.class },
type = FilterType.ASSIGNABLE_TYPE))
static class Config {
}
JpaMetamodelMappingContext context;
@Autowired ProductRepository products;
@Autowired CategoryRepository categories;
@Autowired EntityManager em;
@@ -82,46 +71,46 @@ public class JpaMetamodelMappingContextIntegrationTests {
public void setsUpMappingContextCorrectly() {
JpaPersistentEntityImpl<?> entity = context.getRequiredPersistentEntity(User.class);
assertThat(entity, is(notNullValue()));
assertThat(entity).isNotNull();
}
@Test
public void detectsIdProperty() {
JpaPersistentEntityImpl<?> entity = context.getRequiredPersistentEntity(User.class);
assertThat(entity.getIdProperty(), is(notNullValue()));
assertThat(entity.getIdProperty()).isNotNull();
}
@Test
public void detectsAssociation() {
JpaPersistentEntityImpl<?> entity = context.getRequiredPersistentEntity(User.class);
assertThat(entity, is(notNullValue()));
assertThat(entity).isNotNull();
JpaPersistentProperty property = entity.getRequiredPersistentProperty("manager");
assertThat(property.isAssociation(), is(true));
assertThat(property.isAssociation()).isTrue();
}
@Test
public void detectsPropertyIsEntity() {
JpaPersistentEntityImpl<?> entity = context.getRequiredPersistentEntity(User.class);
assertThat(entity, is(notNullValue()));
assertThat(entity).isNotNull();
JpaPersistentProperty property = entity.getRequiredPersistentProperty("manager");
assertThat(property.isEntity(), is(true));
assertThat(property.isEntity()).isTrue();
property = entity.getRequiredPersistentProperty("lastname");
assertThat(property.isEntity(), is(false));
assertThat(property.isEntity()).isFalse();
}
@Test // DATAJPA-608
public void detectsEntityPropertyForCollections() {
JpaPersistentEntityImpl<?> entity = context.getRequiredPersistentEntity(User.class);
assertThat(entity, is(notNullValue()));
assertThat(entity).isNotNull();
assertThat(entity.getRequiredPersistentProperty("colleagues").isEntity(), is(true));
assertThat(entity.getRequiredPersistentProperty("colleagues").isEntity()).isTrue();
}
@Test // DATAJPA-630
@@ -142,9 +131,9 @@ public class JpaMetamodelMappingContextIntegrationTests {
JpaPersistentEntity<?> entity = context.getRequiredPersistentEntity(Product.class);
IdentifierAccessor accessor = entity.getIdentifierAccessor(loadedProduct);
assertThat(accessor.getIdentifier(), is(category.getProduct().getId()));
assertThat(loadedProduct, is(instanceOf(HibernateProxy.class)));
assertThat(((HibernateProxy) loadedProduct).getHibernateLazyInitializer().isUninitialized(), is(true));
assertThat(accessor.getIdentifier()).isEqualTo(category.getProduct().getId());
assertThat(loadedProduct).isInstanceOf(HibernateProxy.class);
assertThat(((HibernateProxy) loadedProduct).getHibernateLazyInitializer().isUninitialized()).isTrue();
status.setRollbackOnly();
@@ -160,7 +149,7 @@ public class JpaMetamodelMappingContextIntegrationTests {
JpaPersistentEntity<?> entity = context.getPersistentEntity(OrmXmlEntity.class);
assertThat(entity.getIdProperty(), is(notNullValue()));
assertThat(entity.getIdProperty()).isNotNull();
}
@Test // DATAJPA-1320
@@ -184,4 +173,13 @@ public class JpaMetamodelMappingContextIntegrationTests {
assertThat(context.getPersistentPropertyPath("colleagues.firstname", User.class)).isNotNull();
assertThat(paths.contains("colleagues.firstname")).isFalse();
}
@Configuration
@ImportResource("classpath:infrastructure.xml")
@EnableJpaRepositories(basePackageClasses = CategoryRepository.class, //
includeFilters = @Filter(value = { CategoryRepository.class, ProductRepository.class },
type = FilterType.ASSIGNABLE_TYPE))
static class Config {
}
}

View File

@@ -15,9 +15,7 @@
*/
package org.springframework.data.jpa.mapping;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.Collections;
@@ -48,6 +46,7 @@ import org.springframework.data.util.TypeInformation;
*
* @author Oliver Gierke
* @author Greg Turnquist
* @author Jens Schauder
*/
@RunWith(MockitoJUnitRunner.Silent.class)
public class JpaPersistentPropertyImplUnitTests {
@@ -68,64 +67,64 @@ public class JpaPersistentPropertyImplUnitTests {
public void considersOneToOneMappedPropertyAnAssociation() {
JpaPersistentProperty property = entity.getRequiredPersistentProperty("other");
assertThat(property.isAssociation(), is(true));
assertThat(property.isAssociation()).isTrue();
}
@Test // DATAJPA-376
public void considersJpaTransientFieldsAsTransient() {
assertThat(entity.getPersistentProperty("transientProp"), is(nullValue()));
assertThat(entity.getPersistentProperty("transientProp")).isNull();
}
@Test // DATAJPA-484
public void considersEmbeddableAnEntity() {
assertThat(context.getPersistentEntity(SampleEmbeddable.class), is(notNullValue()));
assertThat(context.getPersistentEntity(SampleEmbeddable.class)).isNotNull();
}
@Test // DATAJPA-484
public void doesNotConsiderAnEmbeddablePropertyAnAssociation() {
assertThat(entity.getRequiredPersistentProperty("embeddable").isAssociation(), is(false));
assertThat(entity.getRequiredPersistentProperty("embeddable").isAssociation()).isFalse();
}
@Test // DATAJPA-484
public void doesNotConsiderAnEmbeddedPropertyAnAssociation() {
assertThat(entity.getRequiredPersistentProperty("embedded").isAssociation(), is(false));
assertThat(entity.getRequiredPersistentProperty("embedded").isAssociation()).isFalse();
}
@Test // DATAJPA-619
public void considersPropertyLevelAccessTypeDefinitions() {
assertThat(getProperty(PropertyLevelPropertyAccess.class, "field").usePropertyAccess(), is(false));
assertThat(getProperty(PropertyLevelPropertyAccess.class, "property").usePropertyAccess(), is(true));
assertThat(getProperty(PropertyLevelPropertyAccess.class, "field").usePropertyAccess()).isFalse();
assertThat(getProperty(PropertyLevelPropertyAccess.class, "property").usePropertyAccess()).isTrue();
}
@Test // DATAJPA-619
public void propertyLevelAccessTypeTrumpsTypeLevelDefinition() {
assertThat(getProperty(PropertyLevelDefinitionTrumpsTypeLevelOne.class, "field").usePropertyAccess(), is(false));
assertThat(getProperty(PropertyLevelDefinitionTrumpsTypeLevelOne.class, "property").usePropertyAccess(), is(true));
assertThat(getProperty(PropertyLevelDefinitionTrumpsTypeLevelOne.class, "field").usePropertyAccess()).isFalse();
assertThat(getProperty(PropertyLevelDefinitionTrumpsTypeLevelOne.class, "property").usePropertyAccess()).isTrue();
assertThat(getProperty(PropertyLevelDefinitionTrumpsTypeLevelOne2.class, "field").usePropertyAccess(), is(false));
assertThat(getProperty(PropertyLevelDefinitionTrumpsTypeLevelOne2.class, "property").usePropertyAccess(), is(true));
assertThat(getProperty(PropertyLevelDefinitionTrumpsTypeLevelOne2.class, "field").usePropertyAccess()).isFalse();
assertThat(getProperty(PropertyLevelDefinitionTrumpsTypeLevelOne2.class, "property").usePropertyAccess()).isTrue();
}
@Test // DATAJPA-619
public void considersJpaAccessDefinitionAnnotations() {
assertThat(getProperty(TypeLevelPropertyAccess.class, "id").usePropertyAccess(), is(true));
assertThat(getProperty(TypeLevelPropertyAccess.class, "id").usePropertyAccess()).isTrue();
}
@Test // DATAJPA-619
public void springDataAnnotationTrumpsJpaIfBothOnTypeLevel() {
assertThat(getProperty(CompetingTypeLevelAnnotations.class, "id").usePropertyAccess(), is(false));
assertThat(getProperty(CompetingTypeLevelAnnotations.class, "id").usePropertyAccess()).isFalse();
}
@Test // DATAJPA-619
public void springDataAnnotationTrumpsJpaIfBothOnPropertyLevel() {
assertThat(getProperty(CompetingPropertyLevelAnnotations.class, "id").usePropertyAccess(), is(false));
assertThat(getProperty(CompetingPropertyLevelAnnotations.class, "id").usePropertyAccess()).isFalse();
}
@Test // DATAJPA-605
public void detectsJpaVersionAnnotation() {
assertThat(getProperty(JpaVersioned.class, "version").isVersionProperty(), is(true));
assertThat(getProperty(JpaVersioned.class, "version").isVersionProperty()).isTrue();
}
@Test // DATAJPA-664
@@ -134,18 +133,19 @@ public class JpaPersistentPropertyImplUnitTests {
JpaPersistentProperty property = getProperty(SpecializedAssociation.class, "api");
assertThat(property.getType(), is(typeCompatibleWith(Api.class)));
assertThat(property.getActualType(), is(typeCompatibleWith(Implementation.class)));
assertThat(property.getType()).isEqualTo(Api.class);
assertThat(property.getActualType()).isEqualTo(Implementation.class);
Iterable<? extends TypeInformation<?>> entityType = property.getPersistentEntityTypes();
assertThat(entityType.iterator().hasNext(), is(true));
assertThat(entityType.iterator().next(), is((TypeInformation) ClassTypeInformation.from(Implementation.class)));
assertThat(entityType.iterator().hasNext()).isTrue();
assertThat(entityType.iterator().next())
.isEqualTo((TypeInformation) ClassTypeInformation.from(Implementation.class));
}
@Test // DATAJPA-716
public void considersNonUpdateablePropertyNotWriteable() {
assertThat(getProperty(WithReadOnly.class, "name").isWritable(), is(false));
assertThat(getProperty(WithReadOnly.class, "updatable").isWritable(), is(true));
assertThat(getProperty(WithReadOnly.class, "name").isWritable()).isFalse();
assertThat(getProperty(WithReadOnly.class, "updatable").isWritable()).isTrue();
}
@Test // DATAJPA-904
@@ -154,7 +154,7 @@ public class JpaPersistentPropertyImplUnitTests {
ManagedType<?> managedType = mock(ManagedType.class);
doReturn(Collections.singleton(managedType)).when(model).getManagedTypes();
assertThat(getProperty(Sample.class, "other").isEntity(), is(false));
assertThat(getProperty(Sample.class, "other").isEntity()).isFalse();
}
@Test // DATAJPA-1064
@@ -172,6 +172,8 @@ public class JpaPersistentPropertyImplUnitTests {
return entity.getRequiredPersistentProperty(propertyName);
}
static interface Api {}
static class Sample {
@OneToOne Sample other;
@@ -281,8 +283,6 @@ public class JpaPersistentPropertyImplUnitTests {
@ManyToOne(targetEntity = Implementation.class) Api api;
}
static interface Api {}
static class Implementation {}
static class WithReadOnly {

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.provider;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import javax.persistence.EntityManager;
@@ -30,8 +29,6 @@ import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ImportResource;
import org.springframework.data.jpa.domain.sample.Category;
import org.springframework.data.jpa.domain.sample.Product;
import org.springframework.data.jpa.provider.PersistenceProvider;
import org.springframework.data.jpa.provider.ProxyIdAccessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.jpa.repository.sample.CategoryRepository;
import org.springframework.data.jpa.repository.sample.ProductRepository;
@@ -46,25 +43,16 @@ import org.springframework.transaction.support.TransactionTemplate;
* Integration tests for {@link PersistenceProvider}.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class PersistenceProviderIntegrationTests {
@Configuration
@ImportResource("classpath:infrastructure.xml")
@EnableJpaRepositories(basePackageClasses = CategoryRepository.class,//
includeFilters = @Filter(value = { CategoryRepository.class, ProductRepository.class },
type = FilterType.ASSIGNABLE_TYPE))
static class Config {
}
@Autowired CategoryRepository categories;
@Autowired ProductRepository products;
@Autowired PlatformTransactionManager transactionManager;
@Autowired EntityManager em;
Product product;
Category category;
@@ -85,11 +73,20 @@ public class PersistenceProviderIntegrationTests {
Product product = categories.findById(category.getId()).get().getProduct();
ProxyIdAccessor accessor = PersistenceProvider.fromEntityManager(em);
assertThat(accessor.shouldUseAccessorFor(product), is(true));
assertThat(accessor.getIdentifierFrom(product).toString(), is((Object) product.getId().toString()));
assertThat(accessor.shouldUseAccessorFor(product)).isTrue();
assertThat(accessor.getIdentifierFrom(product).toString()).isEqualTo((Object) product.getId().toString());
return null;
}
});
}
@Configuration
@ImportResource("classpath:infrastructure.xml")
@EnableJpaRepositories(basePackageClasses = CategoryRepository.class, //
includeFilters = @Filter(value = { CategoryRepository.class, ProductRepository.class },
type = FilterType.ASSIGNABLE_TYPE))
static class Config {
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.provider;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.jpa.provider.PersistenceProvider.*;
import static org.springframework.data.jpa.provider.PersistenceProvider.Constants.*;
@@ -25,8 +24,8 @@ import java.util.List;
import javax.persistence.EntityManager;
import org.assertj.core.api.Assumptions;
import org.hibernate.Version;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -61,7 +60,7 @@ public class PersistenceProviderUnitTests {
EntityManager em = mockProviderSpecificEntityManagerInterface(ECLIPSELINK_ENTITY_MANAGER_INTERFACE);
assertThat(fromEntityManager(em), is(ECLIPSELINK));
assertThat(fromEntityManager(em)).isEqualTo(ECLIPSELINK);
}
@Test
@@ -69,19 +68,19 @@ public class PersistenceProviderUnitTests {
EntityManager em = mockProviderSpecificEntityManagerInterface("foo.bar.unknown.jpa.JpaEntityManager");
assertThat(fromEntityManager(em), is(GENERIC_JPA));
assertThat(fromEntityManager(em)).isEqualTo(GENERIC_JPA);
}
@Test // DATAJPA-1019
public void detectsHibernatePersistenceProviderForHibernateVersion52() throws Exception {
Assume.assumeThat(Version.getVersionString(), startsWith("5.2"));
Assumptions.assumeThat(Version.getVersionString()).startsWith("5.2");
shadowingClassLoader.excludePackage("org.hibernate");
EntityManager em = mockProviderSpecificEntityManagerInterface(HIBERNATE_ENTITY_MANAGER_INTERFACE);
assertThat(fromEntityManager(em), is(HIBERNATE));
assertThat(fromEntityManager(em)).isEqualTo(HIBERNATE);
}
@Test // DATAJPA-1379
@@ -94,7 +93,7 @@ public class PersistenceProviderUnitTests {
EntityManager emProxy = Mockito.mock(EntityManager.class);
Mockito.when(emProxy.getDelegate()).thenReturn(em);
assertThat(fromEntityManager(emProxy), is(ECLIPSELINK));
assertThat(fromEntityManager(emProxy)).isEqualTo(ECLIPSELINK);
}
private EntityManager mockProviderSpecificEntityManagerInterface(String interfaceName) throws ClassNotFoundException {

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import javax.persistence.EntityManager;
@@ -35,6 +34,7 @@ import org.springframework.transaction.annotation.Transactional;
*
* @author Thomas Darimont
* @author Oliver Gierke
* @author Jens Schauder
*/
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@@ -51,7 +51,7 @@ public class AbstractPersistableIntegrationTests {
CustomAbstractPersistable saved = repository.save(entity);
CustomAbstractPersistable found = repository.findById(saved.getId()).get();
assertThat(found, is(saved));
assertThat(found).isEqualTo(saved);
}
@Test // DATAJPA-848
@@ -63,6 +63,6 @@ public class AbstractPersistableIntegrationTests {
CustomAbstractPersistable proxy = repository.getOne(entity.getId());
assertThat(proxy, is(proxy));
assertThat(proxy).isEqualTo(proxy);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -30,6 +29,7 @@ import org.springframework.transaction.annotation.Transactional;
/**
* @author Thomas Darimont
* @author Oliver Gierke
* @author Jens Schauder
*/
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@@ -45,6 +45,6 @@ public class CustomAbstractPersistableIntegrationTests {
CustomAbstractPersistable saved = repository.save(entity);
CustomAbstractPersistable found = repository.findById(saved.getId()).get();
assertThat(found, is(saved));
assertThat(found).isEqualTo(saved);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.List;
@@ -40,6 +39,7 @@ import org.springframework.transaction.annotation.Transactional;
* Integration tests for {@link MappedTypeRepository}.
*
* @author Thomas Darimont
* @author Jens Schauder
*/
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@@ -58,8 +58,8 @@ public class MappedTypeRepositoryIntegrationTests {
List<ConcreteType1> concretes1 = concreteRepository1.findAllByAttribute1("foo");
List<ConcreteType2> concretes2 = concreteRepository2.findAllByAttribute1("foo");
assertThat(concretes1.size(), is(1));
assertThat(concretes2.size(), is(1));
assertThat(concretes1.size()).isEqualTo(1);
assertThat(concretes2.size()).isEqualTo(1);
}
@Test // DATAJPA-424
@@ -68,9 +68,9 @@ public class MappedTypeRepositoryIntegrationTests {
concreteRepository1.save(new ConcreteType1("foo"));
concreteRepository2.save(new ConcreteType2("foo"));
Page<ConcreteType2> page = concreteRepository2.findByAttribute1Custom("foo", PageRequest.of(0, 10,
Sort.Direction.DESC, "attribute1"));
Page<ConcreteType2> page = concreteRepository2.findByAttribute1Custom("foo",
PageRequest.of(0, 10, Sort.Direction.DESC, "attribute1"));
assertThat(page.getNumberOfElements(), is(1));
assertThat(page.getNumberOfElements()).isEqualTo(1);
}
}

View File

@@ -15,7 +15,7 @@
*/
package org.springframework.data.jpa.repository;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -28,13 +28,13 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* Simple test case launching an {@code ApplicationContext} to test infrastructure configuration.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:infrastructure.xml")
public class ORMInfrastructureTests {
@Autowired
ApplicationContext context;
@Autowired ApplicationContext context;
/**
* Tests, that the context got initialized and injected correctly.
@@ -44,6 +44,6 @@ public class ORMInfrastructureTests {
@Test
public void contextInitialized() throws Exception {
assertNotNull(context);
assertThat(context).isNotNull();
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Arrays;
import java.util.Collection;
@@ -40,6 +39,7 @@ import org.springframework.test.context.ContextConfiguration;
* Testcase to run {@link UserRepository} integration tests on top of OpenJPA.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
@ContextConfiguration("classpath:openjpa.xml")
public class OpenJpaNamespaceUserRepositoryTests extends NamespaceUserRepositoryTests {
@@ -49,19 +49,12 @@ public class OpenJpaNamespaceUserRepositoryTests extends NamespaceUserRepository
@Test
public void checkQueryValidationWithOpenJpa() {
try {
em.createQuery("something absurd");
fail("Creating query did not validate it");
} catch (Exception e) {
// expected
}
assertThatThrownBy(() -> em.createQuery("something absurd"))
.isInstanceOf(RuntimeException.class);
assertThatThrownBy(() -> em.createNamedQuery("not available"))
.isInstanceOf(RuntimeException.class);
try {
em.createNamedQuery("not available");
fail("Creating invalid named query did not validate it");
} catch (Exception e) {
// expected
}
}
/**
@@ -85,7 +78,7 @@ public class OpenJpaNamespaceUserRepositoryTests extends NamespaceUserRepository
query.setParameter(parameter, Arrays.asList(1, 2));
List<User> resultList = query.getResultList();
assertThat(resultList.size(), is(2));
assertThat(resultList.size()).isEqualTo(2);
}
/**

View File

@@ -15,9 +15,6 @@
*/
package org.springframework.data.jpa.repository;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.util.List;
import java.util.Set;
@@ -42,6 +39,11 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jens Schauder
*/
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:config/namespace-application-context.xml")
@@ -60,7 +62,7 @@ public class ParentRepositoryIntegrationTests {
}
@Test // DATAJPA-287
public void testWithoutJoin() throws Exception {
public void testWithoutJoin() {
Page<Parent> page = repository.findAll(new Specification<Parent>() {
public Predicate toPredicate(Root<Parent> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
@@ -72,11 +74,11 @@ public class ParentRepositoryIntegrationTests {
List<Parent> content = page.getContent();
assertThat(content.size(), is(3));
assertThat(page.getSize(), is(5));
assertThat(page.getNumber(), is(0));
assertThat(page.getTotalElements(), is(3L));
assertThat(page.getTotalPages(), is(1));
assertThat(content.size()).isEqualTo(3);
assertThat(page.getSize()).isEqualTo(5);
assertThat(page.getNumber()).isEqualTo(0);
assertThat(page.getTotalElements()).isEqualTo(3L);
assertThat(page.getTotalPages()).isEqualTo(1);
}
@Test // DATAJPA-287
@@ -94,13 +96,13 @@ public class ParentRepositoryIntegrationTests {
// according to the initial setup there should be
// 3 parents which children collection is not empty
assertThat(content.size(), is(3));
assertThat(page.getSize(), is(5));
assertThat(page.getNumber(), is(0));
assertThat(content.size()).isEqualTo(3);
assertThat(page.getSize()).isEqualTo(5);
assertThat(page.getNumber()).isEqualTo(0);
// we get here wrong total elements number since
// count query doesn't take into account the distinct marker of query
assertThat(page.getTotalElements(), is(3L));
assertThat(page.getTotalPages(), is(1));
assertThat(page.getTotalElements()).isEqualTo(3L);
assertThat(page.getTotalPages()).isEqualTo(1);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.List;
@@ -35,6 +34,7 @@ import org.springframework.transaction.annotation.Transactional;
/**
* @author Thomas Darimont
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SampleConfig.class)
@@ -60,8 +60,8 @@ public class RedeclaringRepositoryMethodsTests {
Page<User> page = repository.findAll(PageRequest.of(0, 2));
assertThat(page.getNumberOfElements(), is(1));
assertThat(page.getContent().get(0).getFirstname(), is("Oliver"));
assertThat(page.getNumberOfElements()).isEqualTo(1);
assertThat(page.getContent().get(0).getFirstname()).isEqualTo("Oliver");
}
@Test // DATAJPA-398
@@ -72,6 +72,6 @@ public class RedeclaringRepositoryMethodsTests {
List<User> result = repository.findAll();
assertThat(result.isEmpty(), is(true));
assertThat(result.isEmpty()).isTrue();
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Arrays;
import java.util.List;
@@ -49,6 +48,7 @@ import org.springframework.transaction.annotation.Transactional;
*
* @author Thomas Darimont
* @author Mark Paluch
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SampleConfig.class)
@@ -81,9 +81,9 @@ public class RepositoryWithCompositeKeyTests {
key.setEmpId(emp.getEmpId());
IdClassExampleEmployee persistedEmp = employeeRepositoryWithIdClass.findById(key).get();
assertThat(persistedEmp, is(notNullValue()));
assertThat(persistedEmp.getDepartment(), is(notNullValue()));
assertThat(persistedEmp.getDepartment().getName(), is(dep.getName()));
assertThat(persistedEmp).isNotNull();
assertThat(persistedEmp.getDepartment()).isNotNull();
assertThat(persistedEmp.getDepartment().getName()).isEqualTo(dep.getName());
}
/**
@@ -108,9 +108,9 @@ public class RepositoryWithCompositeKeyTests {
key.setEmployeeId(emp.getEmployeePk().getEmployeeId());
EmbeddedIdExampleEmployee persistedEmp = employeeRepositoryWithEmbeddedId.findById(key).get();
assertThat(persistedEmp, is(notNullValue()));
assertThat(persistedEmp.getDepartment(), is(notNullValue()));
assertThat(persistedEmp.getDepartment().getName(), is(dep.getName()));
assertThat(persistedEmp).isNotNull();
assertThat(persistedEmp.getDepartment()).isNotNull();
assertThat(persistedEmp.getDepartment().getName()).isEqualTo(dep.getName());
}
@Test // DATAJPA-472, DATAJPA-912
@@ -133,8 +133,8 @@ public class RepositoryWithCompositeKeyTests {
Page<IdClassExampleEmployee> page = employeeRepositoryWithIdClass.findAll(PageRequest.of(0, 1));
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(1L));
assertThat(page).isNotNull();
assertThat(page.getTotalElements()).isEqualTo(1L);
}
@Test // DATAJPA-497
@@ -167,10 +167,10 @@ public class RepositoryWithCompositeKeyTests {
List<EmbeddedIdExampleEmployee> result = employeeRepositoryWithEmbeddedId
.findAll(emp.employeePk.departmentId.eq(dep2.getDepartmentId()), emp.employeePk.employeeId.asc());
assertThat(result, is(notNullValue()));
assertThat(result, hasSize(2));
assertThat(result.get(0), is(emp3));
assertThat(result.get(1), is(emp1));
assertThat(result).isNotNull();
assertThat(result).hasSize(2);
assertThat(result.get(0)).isEqualTo(emp3);
assertThat(result.get(1)).isEqualTo(emp1);
}
@Test // DATAJPA-497
@@ -203,10 +203,10 @@ public class RepositoryWithCompositeKeyTests {
List<IdClassExampleEmployee> result = employeeRepositoryWithIdClass
.findAll(emp.department.departmentId.eq(dep2.getDepartmentId()), emp.empId.asc());
assertThat(result, is(notNullValue()));
assertThat(result, hasSize(2));
assertThat(result.get(0), is(emp3));
assertThat(result.get(1), is(emp1));
assertThat(result).isNotNull();
assertThat(result).hasSize(2);
assertThat(result.get(0)).isEqualTo(emp3);
assertThat(result.get(1)).isEqualTo(emp1);
}
@Test // DATAJPA-527, DATAJPA-1148
@@ -225,8 +225,8 @@ public class RepositoryWithCompositeKeyTests {
key.setDepartment(dep.getDepartmentId());
key.setEmpId(emp.getEmpId());
assertThat(employeeRepositoryWithIdClass.existsById(key), is(true));
assertThat(employeeRepositoryWithIdClass.existsById(new IdClassExampleEmployeePK(0L, 0L)), is(false));
assertThat(employeeRepositoryWithIdClass.existsById(key)).isTrue();
assertThat(employeeRepositoryWithIdClass.existsById(new IdClassExampleEmployeePK(0L, 0L))).isFalse();
}
@Test // DATAJPA-527
@@ -249,7 +249,7 @@ public class RepositoryWithCompositeKeyTests {
key.setDepartmentId(emp.getDepartment().getDepartmentId());
key.setEmployeeId(emp.getEmployeePk().getEmployeeId());
assertThat(employeeRepositoryWithEmbeddedId.existsById(key), is(true));
assertThat(employeeRepositoryWithEmbeddedId.existsById(key)).isTrue();
}
@Test // DATAJPA-611
@@ -283,7 +283,7 @@ public class RepositoryWithCompositeKeyTests {
List<IdClassExampleEmployee> result = employeeRepositoryWithIdClass.findAllById(Arrays.asList(emp1PK, emp2PK));
assertThat(result, hasSize(2));
assertThat(result).hasSize(2);
}
@Test // DATAJPA-920
@@ -304,7 +304,7 @@ public class RepositoryWithCompositeKeyTests {
employeeRepositoryWithEmbeddedId.save(emp);
assertThat(employeeRepositoryWithEmbeddedId.existsByName(emp.getName()), is(true));
assertThat(employeeRepositoryWithEmbeddedId.existsByName(emp.getName())).isTrue();
}
@Test // DATAJPA-920
@@ -321,7 +321,7 @@ public class RepositoryWithCompositeKeyTests {
employeeRepositoryWithIdClass.save(emp1);
assertThat(employeeRepositoryWithIdClass.existsByName(emp1.getName()), is(true));
assertThat(employeeRepositoryWithIdClass.existsByName("Walter"), is(false));
assertThat(employeeRepositoryWithIdClass.existsByName(emp1.getName())).isTrue();
assertThat(employeeRepositoryWithIdClass.existsByName("Walter")).isFalse();
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Optional;
@@ -24,7 +23,6 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@@ -46,6 +44,7 @@ import org.springframework.transaction.annotation.Transactional;
* Integration tests for Repositories using {@link javax.persistence.IdClass} identifiers.
*
* @author Mark Paluch
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RepositoryWithIdClassKeyTests.TestConfig.class)
@@ -60,15 +59,6 @@ public class RepositoryWithIdClassKeyTests {
@Autowired private ItemSiteRepository itemSiteRepository;
@Configuration
@EnableJpaRepositories(basePackageClasses = SampleConfig.class)
static abstract class Config {
}
@ImportResource("classpath:infrastructure.xml")
static class TestConfig extends Config {}
/**
* @see <a href="download.oracle.com/otn-pub/jcp/persistence-2_1-fr-eval-spec/JavaPersistence.pdf">Final JPA 2.1
* Specification 2.4.1.3 Derived Identities Example 2</a>
@@ -84,7 +74,16 @@ public class RepositoryWithIdClassKeyTests {
Optional<ItemSite> loaded = itemSiteRepository
.findById(new ItemSiteId(new ItemId(item.getId(), item.getManufacturerId()), site.getId()));
assertThat(loaded, is(notNullValue()));
assertThat(loaded.isPresent(), is(true));
assertThat(loaded).isNotNull();
assertThat(loaded.isPresent()).isTrue();
}
@Configuration
@EnableJpaRepositories(basePackageClasses = SampleConfig.class)
static abstract class Config {
}
@ImportResource("classpath:infrastructure.xml")
static class TestConfig extends Config {}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Optional;
@@ -35,6 +34,7 @@ import org.springframework.transaction.annotation.Transactional;
*
* @author Oliver Gierke
* @author Thomas Darimont
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:application-context.xml" })
@@ -48,7 +48,7 @@ public class RoleRepositoryIntegrationTests {
Role reference = new Role("ADMIN");
Role result = repository.save(reference);
assertThat(result, is(reference));
assertThat(result).isEqualTo(reference);
}
@Test
@@ -56,13 +56,13 @@ public class RoleRepositoryIntegrationTests {
Role reference = new Role("ADMIN");
Role result = repository.save(reference);
assertThat(result, is(reference));
assertThat(result).isEqualTo(reference);
// Change role name
ReflectionTestUtils.setField(reference, "name", "USER");
repository.save(reference);
assertThat(repository.findById(result.getId()), is(Optional.of(reference)));
assertThat(repository.findById(result.getId())).isEqualTo(Optional.of(reference));
}
@Test // DATAJPA-509
@@ -71,7 +71,7 @@ public class RoleRepositoryIntegrationTests {
Role reference = new Role("ADMIN");
repository.save(reference);
assertThat(repository.count(), is(1L));
assertThat(repository.count()).isEqualTo(1L);
}
@Test // DATAJPA-509
@@ -80,7 +80,7 @@ public class RoleRepositoryIntegrationTests {
Role reference = new Role("ADMIN");
reference = repository.save(reference);
assertThat(repository.existsById(reference.getId()), is(true));
assertThat(repository.existsById(reference.getId())).isTrue();
}
@Test // DATAJPA-509
@@ -89,6 +89,6 @@ public class RoleRepositoryIntegrationTests {
Role reference = new Role("ADMIN");
reference = repository.save(reference);
assertThat(repository.countByName(reference.getName()), is(1L));
assertThat(repository.countByName(reference.getName())).isEqualTo(1L);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Arrays;
import java.util.Map;
@@ -30,13 +29,14 @@ import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.support.RepositoryFactoryInformation;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:config/namespace-application-context.xml")
public class SPR8954Tests {
@Autowired
ApplicationContext context;
@Autowired ApplicationContext context;
@Test
@SuppressWarnings("rawtypes")
@@ -45,9 +45,9 @@ public class SPR8954Tests {
Map<String, RepositoryFactoryInformation> repoFactories = context
.getBeansOfType(RepositoryFactoryInformation.class);
assertThat(repoFactories.size(), is(greaterThan(0)));
assertThat(repoFactories.keySet(), hasItem("&userRepository"));
assertThat(repoFactories.get("&userRepository"), is(instanceOf(JpaRepositoryFactoryBean.class)));
assertThat(Arrays.asList(context.getBeanNamesForType(UserRepository.class)), hasItem("userRepository"));
assertThat(repoFactories.size()).isGreaterThan(0);
assertThat(repoFactories.keySet()).contains("&userRepository");
assertThat(repoFactories.get("&userRepository")).isInstanceOf(JpaRepositoryFactoryBean.class);
assertThat(Arrays.asList(context.getBeanNamesForType(UserRepository.class))).contains("userRepository");
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Arrays;
import java.util.Collection;
@@ -40,17 +39,17 @@ import org.springframework.transaction.annotation.Transactional;
/**
* @author Oliver Gierke
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:application-context.xml"
// , "classpath:eclipselink.xml"
// , "classpath:openjpa.xml"
// , "classpath:eclipselink.xml"
// , "classpath:openjpa.xml"
})
@Transactional
public class SimpleJpaParameterBindingTests {
@PersistenceContext
EntityManager em;
@PersistenceContext EntityManager em;
@Test
@Ignore
@@ -71,7 +70,7 @@ public class SimpleJpaParameterBindingTests {
query.setParameter(parameter, new String[] { "Dave", "Carter" });
List<User> result = query.getResultList();
assertThat(result.isEmpty(), is(false));
assertThat(result.isEmpty()).isFalse();
}
@Test
@@ -94,7 +93,7 @@ public class SimpleJpaParameterBindingTests {
query.setParameter(parameter, Arrays.asList("Dave"));
List<User> result = query.getResultList();
assertThat(result.isEmpty(), is(false));
assertThat(result.get(0), is(user));
assertThat(result.isEmpty()).isFalse();
assertThat(result.get(0)).isEqualTo(user);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.junit.Assume.*;
import static org.springframework.data.jpa.support.EntityManagerTestUtils.*;
@@ -46,6 +45,7 @@ import org.springframework.transaction.annotation.Transactional;
*
* @author Thomas Darimont
* @author Oliver Gierke
* @author Jens Schauder
* @see scripts/schema-stored-procedures.sql for procedure definitions.
*/
@Transactional
@@ -58,14 +58,6 @@ public class StoredProcedureIntegrationTests {
@PersistenceContext EntityManager em;
@Autowired DummyRepository repository;
@Configuration
@EnableJpaRepositories(basePackageClasses = DummyRepository.class, includeFilters = { @Filter(
pattern = ".*DummyRepository", type = FilterType.REGEX) })
static abstract class Config {}
@ImportResource("classpath:infrastructure.xml")
static class TestConfig extends Config {}
@Before
public void setup() {
assumeTrue(currentEntityManagerIsAJpa21EntityManager(em));
@@ -73,12 +65,12 @@ public class StoredProcedureIntegrationTests {
@Test // DATAJPA-652
public void shouldExecuteAdHocProcedureWithNoInputAnd1OutputParameter() {
assertThat(repository.adHocProcedureWithNoInputAnd1OutputParameter(), is(42));
assertThat(repository.adHocProcedureWithNoInputAnd1OutputParameter()).isEqualTo(42);
}
@Test // DATAJPA-652
public void shouldExecuteAdHocProcedureWith1InputAnd1OutputParameter() {
assertThat(repository.adHocProcedureWith1InputAnd1OutputParameter(23), is(24));
assertThat(repository.adHocProcedureWith1InputAnd1OutputParameter(23)).isEqualTo(24);
}
@Test // DATAJPA-652
@@ -92,8 +84,8 @@ public class StoredProcedureIntegrationTests {
List<Dummy> dummies = repository.adHocProcedureWith1InputAnd1OutputParameterWithResultSet("FOO");
assertThat(dummies, is(notNullValue()));
assertThat(dummies.size(), is(equalTo(3)));
assertThat(dummies).isNotNull();
assertThat(dummies.size()).isEqualTo(3);
}
@Test // DATAJPA-652
@@ -102,8 +94,8 @@ public class StoredProcedureIntegrationTests {
List<Dummy> dummies = repository.adHocProcedureWith1InputAnd1OutputParameterWithResultSetWithUpdate("FOO");
assertThat(dummies, is(notNullValue()));
assertThat(dummies.size(), is(equalTo(3)));
assertThat(dummies).isNotNull();
assertThat(dummies.size()).isEqualTo(3);
}
@Test // DATAJPA-652
@@ -113,12 +105,12 @@ public class StoredProcedureIntegrationTests {
@Test // DATAJPA-652
public void shouldExecuteProcedureWithNoInputAnd1OutputParameter() {
assertThat(repository.procedureWithNoInputAnd1OutputParameter(), is(42));
assertThat(repository.procedureWithNoInputAnd1OutputParameter()).isEqualTo(42);
}
@Test // DATAJPA-652
public void shouldExecuteProcedureWith1InputAnd1OutputParameter() {
assertThat(repository.procedureWith1InputAnd1OutputParameter(23), is(24));
assertThat(repository.procedureWith1InputAnd1OutputParameter(23)).isEqualTo(24);
}
@Test // DATAJPA-652
@@ -132,8 +124,8 @@ public class StoredProcedureIntegrationTests {
List<Dummy> dummies = repository.procedureWith1InputAnd1OutputParameterWithResultSet("FOO");
assertThat(dummies, is(notNullValue()));
assertThat(dummies.size(), is(equalTo(3)));
assertThat(dummies).isNotNull();
assertThat(dummies.size()).isEqualTo(3);
}
@Test // DATAJPA-652
@@ -142,12 +134,20 @@ public class StoredProcedureIntegrationTests {
List<Dummy> dummies = repository.procedureWith1InputAnd1OutputParameterWithResultSetWithUpdate("FOO");
assertThat(dummies, is(notNullValue()));
assertThat(dummies.size(), is(equalTo(3)));
assertThat(dummies).isNotNull();
assertThat(dummies.size()).isEqualTo(3);
}
@Test // DATAJPA-652
public void shouldExecuteProcedureWith1InputAnd1OutputParameterWithUpdate() {
repository.procedureWith1InputAndNoOutputParameterWithUpdate("FOO");
}
@Configuration
@EnableJpaRepositories(basePackageClasses = DummyRepository.class,
includeFilters = { @Filter(pattern = ".*DummyRepository", type = FilterType.REGEX) })
static abstract class Config {}
@ImportResource("classpath:infrastructure.xml")
static class TestConfig extends Config {}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.cdi;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Set;
@@ -36,12 +35,12 @@ import org.slf4j.LoggerFactory;
* @author Dirk Mahler
* @author Oliver Gierke
* @author Mark Paluch
* @author Jens Schauder
*/
public class CdiExtensionIntegrationTests {
private static Logger LOGGER = LoggerFactory.getLogger(CdiExtensionIntegrationTests.class);
static SeContainer container;
private static Logger LOGGER = LoggerFactory.getLogger(CdiExtensionIntegrationTests.class);
@BeforeClass
public static void setUp() {
@@ -60,8 +59,8 @@ public class CdiExtensionIntegrationTests {
Set<Bean<?>> beans = container.getBeanManager().getBeans(PersonRepository.class);
assertThat(beans, hasSize(1));
assertThat(beans.iterator().next().getScope(), is(equalTo((Class) ApplicationScoped.class)));
assertThat(beans).hasSize(1);
assertThat(beans.iterator().next().getScope()).isEqualTo((Class) ApplicationScoped.class);
}
@Test // DATAJPA-136, DATAJPA-1180
@@ -78,7 +77,7 @@ public class CdiExtensionIntegrationTests {
public void returnOneFromCustomImpl() {
RepositoryConsumer repositoryConsumer = container.select(RepositoryConsumer.class).get();
assertThat(repositoryConsumer.returnOne(), is(1));
assertThat(repositoryConsumer.returnOne()).isEqualTo(1);
}
@Test // DATAJPA-584, DATAJPA-1180
@@ -92,6 +91,6 @@ public class CdiExtensionIntegrationTests {
public void useQualifiedFragmentUserRepo() {
RepositoryConsumer repositoryConsumer = container.select(RepositoryConsumer.class).get();
assertThat(repositoryConsumer.returnOneUserDB(), is(1));
assertThat(repositoryConsumer.returnOneUserDB()).isEqualTo(1);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.cdi;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.lang.annotation.Annotation;
@@ -37,11 +36,30 @@ import org.springframework.test.util.ReflectionTestUtils;
* Unit tests for {@link JpaRepositoryExtension}.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
public class JpaRepositoryExtensionUnitTests {
Bean<EntityManager> em, alternativeEm;
@SuppressWarnings("unchecked")
private static void assertEntityManagerRegistered(JpaRepositoryExtension extension, Bean<EntityManager> em) {
Map<Set<Annotation>, Bean<EntityManager>> entityManagers = (Map<Set<Annotation>, Bean<EntityManager>>) ReflectionTestUtils
.getField(extension, "entityManagers");
assertThat(entityManagers.size()).isEqualTo(1);
assertThat(entityManagers.values()).contains(em);
}
@SuppressWarnings("unchecked")
private static ProcessBean<EntityManager> createEntityManagerBeanMock(Bean<EntityManager> bean) {
ProcessBean<EntityManager> mock = mock(ProcessBean.class);
when(mock.getBean()).thenReturn(bean);
return mock;
}
@Before
@SuppressWarnings("unchecked")
public void setUp() {
@@ -85,22 +103,4 @@ public class JpaRepositoryExtensionUnitTests {
assertEntityManagerRegistered(extension, alternativeEm);
}
@SuppressWarnings("unchecked")
private static void assertEntityManagerRegistered(JpaRepositoryExtension extension, Bean<EntityManager> em) {
Map<Set<Annotation>, Bean<EntityManager>> entityManagers = (Map<Set<Annotation>, Bean<EntityManager>>) ReflectionTestUtils
.getField(extension, "entityManagers");
assertThat(entityManagers.size(), is(1));
assertThat(entityManagers.values(), hasItem(em));
}
@SuppressWarnings("unchecked")
private static ProcessBean<EntityManager> createEntityManagerBeanMock(Bean<EntityManager> bean) {
ProcessBean<EntityManager> mock = mock(ProcessBean.class);
when(mock.getBean()).thenReturn(bean);
return mock;
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.config;
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.LocalDateTime;
@@ -53,6 +52,7 @@ import org.springframework.transaction.annotation.Transactional;
*
* @author Thomas Darimont
* @author Oliver Gierke
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@@ -65,17 +65,6 @@ public abstract class AbstractAuditingViaJavaConfigRepositoriesTests {
@Autowired EntityManager em;
@Configuration
@Import(InfrastructureConfig.class)
@EnableJpaRepositories(basePackageClasses = AuditableUserRepository.class)
static class TestConfig {
@Bean
EvaluationContextExtension sampleEvaluationContextExtension() {
return new SampleEvaluationContextExtension();
}
}
@Before
public void setup() {
@@ -101,12 +90,12 @@ public abstract class AbstractAuditingViaJavaConfigRepositoriesTests {
AuditableUser savedUser = auditableUserRepository.save(user);
TimeUnit.MILLISECONDS.sleep(10);
assertThat(savedUser.getCreatedDate(), is(notNullValue()));
assertThat(savedUser.getCreatedDate().get().isBefore(LocalDateTime.now()), is(true));
assertThat(savedUser.getCreatedDate()).isNotNull();
assertThat(savedUser.getCreatedDate().get().isBefore(LocalDateTime.now())).isTrue();
AuditableUser createdBy = savedUser.getCreatedBy().get();
assertThat(createdBy, is(notNullValue()));
assertThat(createdBy.getFirstname(), is(this.auditor.getFirstname()));
assertThat(createdBy).isNotNull();
assertThat(createdBy.getFirstname()).isEqualTo(this.auditor.getFirstname());
}
@Test // DATAJPA-382
@@ -132,9 +121,20 @@ public abstract class AbstractAuditingViaJavaConfigRepositoriesTests {
for (AuditableUser user : users) {
assertThat(user.getFirstname(), is(user.getFirstname().toUpperCase()));
assertThat(user.getLastModifiedBy(), is(Optional.of(thomas)));
assertThat(user.getLastModifiedDate(), is(Optional.of(now)));
assertThat(user.getFirstname()).isEqualTo(user.getFirstname().toUpperCase());
assertThat(user.getLastModifiedBy()).isEqualTo(Optional.of(thomas));
assertThat(user.getLastModifiedDate()).isEqualTo(Optional.of(now));
}
}
@Configuration
@Import(InfrastructureConfig.class)
@EnableJpaRepositories(basePackageClasses = AuditableUserRepository.class)
static class TestConfig {
@Bean
EvaluationContextExtension sampleEvaluationContextExtension() {
return new SampleEvaluationContextExtension();
}
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.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.springframework.beans.factory.annotation.Autowired;
@@ -28,6 +27,7 @@ import org.springframework.test.context.ContextConfiguration;
*
* @author Thomas Darimont
* @author Oliver Gierke
* @author Jens Schauder
*/
@ContextConfiguration(locations = "classpath:config/namespace-nested-repositories-application-context.xml")
public class AllowNestedRepositoriesRepositoryConfigTests extends AbstractRepositoryConfigTests {
@@ -36,6 +36,6 @@ public class AllowNestedRepositoriesRepositoryConfigTests extends AbstractReposi
@Test // DATAJPA-416
public void shouldFindNestedRepository() {
assertThat(fooRepository, is(notNullValue()));
assertThat(fooRepository).isNotNull();
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.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.springframework.beans.PropertyValue;
@@ -34,6 +33,7 @@ import org.springframework.instrument.classloading.ShadowingClassLoader;
*
* @author Oliver Gierke
* @author Thomas Darimont
* @author Jens Schauder
*/
public class AuditingBeanDefinitionParserTests {
@@ -53,13 +53,13 @@ public class AuditingBeanDefinitionParserTests {
BeanDefinition definition = getBeanDefinition("auditing/auditing-namespace-context3.xml");
PropertyValue value = definition.getPropertyValues().getPropertyValue("dateTimeProvider");
assertThat(value, is(notNullValue()));
assertThat(value.getValue(), is(instanceOf(RuntimeBeanReference.class)));
assertThat(((RuntimeBeanReference) value.getValue()).getBeanName(), is("dateTimeProvider"));
assertThat(value).isNotNull();
assertThat(value.getValue()).isInstanceOf(RuntimeBeanReference.class);
assertThat(((RuntimeBeanReference) value.getValue()).getBeanName()).isEqualTo("dateTimeProvider");
BeanFactory factory = loadFactoryFrom("auditing/auditing-namespace-context3.xml");
Object bean = factory.getBean(AuditingBeanDefinitionParser.AUDITING_ENTITY_LISTENER_CLASS_NAME);
assertThat(bean, is(notNullValue()));
assertThat(bean).isNotNull();
}
@Test(expected = BeanDefinitionParsingException.class) // DATAJPA-367
@@ -74,8 +74,8 @@ public class AuditingBeanDefinitionParserTests {
BeanDefinition definition = getBeanDefinition(configFile);
PropertyValue propertyValue = definition.getPropertyValues().getPropertyValue("dateTimeForNow");
assertThat(propertyValue, is(notNullValue()));
assertThat((String) propertyValue.getValue(), is(value));
assertThat(propertyValue).isNotNull();
assertThat((String) propertyValue.getValue()).isEqualTo(value);
}
private BeanDefinition getBeanDefinition(String configFile) {

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.config;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Before;
import org.junit.Test;
@@ -38,6 +37,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
*
* @author Oliver Gierke
* @author Mark Paluch
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:config/namespace-customfactory-context.xml")
@@ -63,8 +63,8 @@ public class CustomRepositoryFactoryConfigTests {
userRepository.findAll();
assertFalse(transactionManager.getDefinition().isReadOnly());
assertThat(transactionManager.getDefinition().getTimeout(), is(10));
assertThat(transactionManager.getDefinition().isReadOnly()).isFalse();
assertThat(transactionManager.getDefinition().getTimeout()).isEqualTo(10);
}
@Test
@@ -72,7 +72,7 @@ public class CustomRepositoryFactoryConfigTests {
userRepository.findById(1);
assertFalse(transactionManager.getDefinition().isReadOnly());
assertThat(transactionManager.getDefinition().getTimeout(), is(10));
assertThat(transactionManager.getDefinition().isReadOnly()).isFalse();
assertThat(transactionManager.getDefinition().getTimeout()).isEqualTo(10);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.config;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Arrays;
import java.util.List;
@@ -24,7 +23,6 @@ import java.util.List;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.aop.Advisor;
@@ -97,14 +95,14 @@ public class JpaRepositoriesRegistrarIntegrationTests {
@Test
public void foo() {
assertThat(repository, is(notNullValue()));
assertThat(repository).isNotNull();
}
@Test // DATAJPA-330
public void doesNotProxyPlainAtRepositoryBeans() {
assertThat(sampleRepository, is(notNullValue()));
assertThat(ClassUtils.isCglibProxy(sampleRepository), is(false));
assertThat(sampleRepository).isNotNull();
assertThat(ClassUtils.isCglibProxy(sampleRepository)).isFalse();
assertExceptionTranslationActive(repository);
}
@@ -120,9 +118,11 @@ public class JpaRepositoriesRegistrarIntegrationTests {
return;
}
assertThat(repository, is(instanceOf(Advised.class)));
assertThat(repository).isInstanceOf(Advised.class);
List<Advisor> advisors = Arrays.asList(((Advised) repository).getAdvisors());
assertThat(advisors, Matchers.<Advisor> hasItem(Matchers.<Advisor> hasProperty("advice",
instanceOf(PersistenceExceptionTranslationInterceptor.class))));
assertThat(advisors) //
.extracting("advice") //
.hasAtLeastOneElementOfType(PersistenceExceptionTranslationInterceptor.class);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.config;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Arrays;
@@ -34,6 +33,7 @@ import org.springframework.data.jpa.repository.sample.UserRepository;
* Unit test for {@link JpaRepositoriesRegistrar}.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
public class JpaRepositoriesRegistrarUnitTests {
@@ -56,7 +56,7 @@ public class JpaRepositoriesRegistrarUnitTests {
registrar.registerBeanDefinitions(metadata, registry);
Iterable<String> names = Arrays.asList(registry.getBeanDefinitionNames());
assertThat(names, hasItems("userRepository", "auditableUserRepository", "roleRepository"));
assertThat(names).contains("userRepository", "auditableUserRepository", "roleRepository");
}
@EnableJpaRepositories(basePackageClasses = UserRepository.class)

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.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.springframework.beans.PropertyValue;
@@ -29,6 +28,7 @@ import org.springframework.core.io.ClassPathResource;
* Integration test for {@link JpaRepositoryConfigDefinitionParser}.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
public class JpaRepositoryConfigDefinitionParserTests {
@@ -40,10 +40,10 @@ public class JpaRepositoryConfigDefinitionParserTests {
reader.loadBeanDefinitions(new ClassPathResource("multiple-entity-manager-integration-context.xml"));
BeanDefinition definition = factory.getBeanDefinition("auditableUserRepository");
assertThat(definition, is(notNullValue()));
assertThat(definition).isNotNull();
PropertyValue transactionManager = definition.getPropertyValues().getPropertyValue("transactionManager");
assertThat(transactionManager, is(notNullValue()));
assertThat(transactionManager.getValue().toString(), is("transactionManager-2"));
assertThat(transactionManager).isNotNull();
assertThat(transactionManager.getValue().toString()).isEqualTo("transactionManager-2");
}
}

View File

@@ -15,9 +15,7 @@
*/
package org.springframework.data.jpa.repository.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.Arrays;
@@ -49,13 +47,13 @@ import org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcesso
*
* @author Oliver Gierke
* @author Mark Paluch
* @author Jens Schauder
*/
@RunWith(MockitoJUnitRunner.class)
public class JpaRepositoryConfigExtensionUnitTests {
@Mock RepositoryConfigurationSource configSource;
public @Rule ExpectedException exception = ExpectedException.none();
@Mock RepositoryConfigurationSource configSource;
@Test
public void registersDefaultBeanPostProcessorsByDefault() {
@@ -67,7 +65,7 @@ public class JpaRepositoryConfigExtensionUnitTests {
Iterable<String> names = Arrays.asList(factory.getBeanDefinitionNames());
assertThat(names, hasItems(AnnotationConfigUtils.PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
assertThat(names).contains(AnnotationConfigUtils.PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME);
}
@Test
@@ -148,7 +146,7 @@ public class JpaRepositoryConfigExtensionUnitTests {
RepositoryConfigurationExtension extension = new JpaRepositoryConfigExtension();
extension.registerBeansForRoot(factory, configSource);
assertThat(factory.getBean(expectedBeanName), is(notNullValue()));
assertThat(factory.getBean(expectedBeanName)).isNotNull();
exception.expect(NoSuchBeanDefinitionException.class);
factory.getBeanDefinition("org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor#1");
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.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;
@@ -34,20 +33,21 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
*
* @author Thomas Darimont
* @author Oliver Gierke
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class NestedRepositoriesJavaConfigTests {
@Configuration
@EnableJpaRepositories(basePackageClasses = UserRepository.class, considerNestedRepositories = true)
@ImportResource("classpath:infrastructure.xml")
static class Config {}
@Autowired NestedUserRepository nestedUserRepository;
@Test // DATAJPA-416
public void shouldSupportNestedRepositories() {
assertThat(nestedUserRepository, is(notNullValue()));
assertThat(nestedUserRepository).isNotNull();
}
@Configuration
@EnableJpaRepositories(basePackageClasses = UserRepository.class, considerNestedRepositories = true)
@ImportResource("classpath:infrastructure.xml")
static class Config {}
}

View File

@@ -15,7 +15,7 @@
*/
package org.springframework.data.jpa.repository.config;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.test.util.ReflectionTestUtils.*;
import org.junit.Test;
@@ -33,6 +33,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
*
* @author Oliver Gierke
* @author Thomas Darimont
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:config/lookup-strategies-context.xml")
@@ -48,6 +49,6 @@ public class QueryLookupStrategyTests {
JpaRepositoryFactoryBean<?, ?, ?> factory = context.getBean("&roleRepository", JpaRepositoryFactoryBean.class);
assertEquals(Key.CREATE_IF_NOT_FOUND, getField(factory, "queryLookupStrategyKey"));
assertThat(getField(factory, "queryLookupStrategyKey")).isEqualTo(Key.CREATE_IF_NOT_FOUND);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.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;
@@ -35,30 +34,29 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* Integration test for the combination of JavaConfig and an {@link Repositories} wrapper.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class RepositoriesJavaConfigTests {
@Autowired Repositories repositories;
@Test // DATAJPA-323
public void foo() {
assertThat(repositories.hasRepositoryFor(User.class)).isTrue();
}
@Configuration
@EnableJpaRepositories(basePackageClasses = UserRepository.class)
@ImportResource("classpath:infrastructure.xml")
static class Config {
@Autowired
ApplicationContext context;
@Autowired ApplicationContext context;
@Bean
public Repositories repositories() {
return new Repositories(context);
}
}
@Autowired
Repositories repositories;
@Test // DATAJPA-323
public void foo() {
assertThat(repositories.hasRepositoryFor(User.class), is(true));
}
}

View File

@@ -15,7 +15,7 @@
*/
package org.springframework.data.jpa.repository.config;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.springframework.test.context.ContextConfiguration;
@@ -23,6 +23,7 @@ import org.springframework.test.context.ContextConfiguration;
* Integration test to test {@link org.springframework.core.type.filter.TypeFilter} integration into namespace.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
@ContextConfiguration(locations = "classpath:config/namespace-autoconfig-typefilter-context.xml")
public class TypeFilterConfigTests extends AbstractRepositoryConfigTests {
@@ -37,8 +38,8 @@ public class TypeFilterConfigTests extends AbstractRepositoryConfigTests {
@Override
public void testContextCreation() {
assertNotNull(userRepository);
assertNotNull(roleRepository);
assertNull(auditableUserRepository);
assertThat(userRepository).isNotNull();
assertThat(roleRepository).isNotNull();
assertThat(auditableUserRepository).isNull();
}
}

View File

@@ -15,15 +15,13 @@
*/
package org.springframework.data.jpa.repository.query;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.expression.spel.standard.SpelExpressionParser;
/**
@@ -31,13 +29,13 @@ import org.springframework.expression.spel.standard.SpelExpressionParser;
*
* @author Thomas Darimont
* @author Oliver Gierke
* @author Jens Schauder
*/
@RunWith(MockitoJUnitRunner.class)
public class ExpressionBasedStringQueryUnitTests {
@Mock JpaEntityMetadata<?> metadata;
static final SpelExpressionParser SPEL_PARSER = new SpelExpressionParser();
@Mock JpaEntityMetadata<?> metadata;
@Test // DATAJPA-170
public void shouldReturnQueryWithDomainTypeExpressionReplacedWithSimpleDomainTypeName() {
@@ -46,7 +44,7 @@ public class ExpressionBasedStringQueryUnitTests {
String source = "select from #{#entityName} u where u.firstname like :firstname";
StringQuery query = new ExpressionBasedStringQuery(source, metadata, SPEL_PARSER);
assertThat(query.getQueryString(), is("select from User u where u.firstname like :firstname"));
assertThat(query.getQueryString()).isEqualTo("select from User u where u.firstname like :firstname");
}
@Test // DATAJPA-424
@@ -55,8 +53,8 @@ public class ExpressionBasedStringQueryUnitTests {
when(metadata.getEntityName()).thenReturn("User");
StringQuery query = new ExpressionBasedStringQuery("select u from #{#entityName} u", metadata, SPEL_PARSER);
assertThat(query.getAlias(), is("u"));
assertThat(query.getQueryString(), is("select u from User u"));
assertThat(query.getAlias()).isEqualTo("u");
assertThat(query.getQueryString()).isEqualTo("select u from User u");
}
}

View File

@@ -15,27 +15,39 @@
*/
package org.springframework.data.jpa.repository.query;
import static org.junit.Assert.*;
import static org.junit.Assume.*;
import static org.springframework.data.jpa.support.EntityManagerTestUtils.*;
import static org.springframework.data.jpa.util.IsAttributeNode.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.persistence.AttributeNode;
import javax.persistence.EntityGraph;
import javax.persistence.EntityManager;
import javax.persistence.Subgraph;
import org.assertj.core.api.AbstractAssert;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.SoftAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.sample.User;
import org.springframework.data.jpa.repository.EntityGraph.EntityGraphType;
import org.springframework.lang.Nullable;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
/**
* @author Christoph Strobl
* @author Mark Paluch
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application-context.xml")
@@ -54,10 +66,10 @@ public class Jpa21UtilsTests {
new JpaEntityGraph("name", EntityGraphType.FETCH, new String[] { "roles", "colleagues" }), graph);
AttributeNode<?> roles = findNode("roles", graph);
assertThat(roles, terminatesGraph());
assertThat(roles).terminatesGraph();
AttributeNode<?> colleagues = findNode("colleagues", graph);
assertThat(colleagues, terminatesGraph());
assertThat(colleagues).terminatesGraph();
}
@Test // DATAJPA-1041, DATAJPA-1075
@@ -70,10 +82,11 @@ public class Jpa21UtilsTests {
new String[] { "roles", "colleagues.roles", "colleagues.colleagues" }), graph);
AttributeNode<?> roles = findNode("roles", graph);
assertThat(roles, terminatesGraph());
assertThat(roles).terminatesGraph();
AttributeNode<?> colleagues = findNode("colleagues", graph);
assertThat(colleagues, terminatesGraphWith("roles", "colleagues"));
assertThat(colleagues).terminatesGraphWith("roles", "colleagues");
}
@Test // DATAJPA-1041, DATAJPA-1075
@@ -86,14 +99,16 @@ public class Jpa21UtilsTests {
new String[] { "roles", "colleagues.roles", "colleagues.colleagues.roles" }), graph);
AttributeNode<?> roles = findNode("roles", graph);
assertThat(roles, terminatesGraph());
assertThat(roles).terminatesGraph();
AttributeNode<?> colleagues = findNode("colleagues", graph);
assertThat(colleagues, terminatesGraphWith("roles"));
assertThat(colleagues, hasSubgraphs("colleagues"));
assertThat(colleagues) //
.terminatesGraphWith("roles") //
.hasSubgraphs("colleagues");
AttributeNode<?> colleaguesOfColleagues = findNode("colleagues", colleagues);
assertThat(colleaguesOfColleagues, terminatesGraphWith("roles"));
assertThat(colleaguesOfColleagues).terminatesGraphWith("roles");
}
@Test // DATAJPA-1041, DATAJPA-1075
@@ -106,14 +121,16 @@ public class Jpa21UtilsTests {
"colleagues", "colleagues.roles", "colleagues.colleagues", "colleagues.colleagues.roles" }), graph);
AttributeNode<?> roles = findNode("roles", graph);
assertThat(roles, terminatesGraph());
assertThat(roles).terminatesGraph();
AttributeNode<?> colleagues = findNode("colleagues", graph);
assertThat(colleagues, terminatesGraphWith("roles"));
assertThat(colleagues, hasSubgraphs("colleagues"));
assertThat(colleagues).terminatesGraphWith("roles");
assertThat(colleagues).hasSubgraphs("colleagues");
AttributeNode<?> colleaguesOfColleagues = findNode("colleagues", colleagues);
assertThat(colleaguesOfColleagues, terminatesGraphWith("roles"));
assertThat(colleaguesOfColleagues).terminatesGraphWith("roles");
}
@Test // DATAJPA-1041, DATAJPA-1075
@@ -126,14 +143,15 @@ public class Jpa21UtilsTests {
"colleagues.colleagues.roles", "roles", "colleagues.colleagues", "colleagues", "colleagues.roles" }), graph);
AttributeNode<?> roles = findNode("roles", graph);
assertThat(roles, terminatesGraph());
assertThat(roles).terminatesGraph();
AttributeNode<?> colleagues = findNode("colleagues", graph);
assertThat(colleagues, terminatesGraphWith("roles"));
assertThat(colleagues, hasSubgraphs("colleagues"));
assertThat(colleagues) //
.terminatesGraphWith("roles") //
.hasSubgraphs("colleagues");
AttributeNode<?> colleaguesOfColleagues = findNode("colleagues", colleagues);
assertThat(colleaguesOfColleagues, terminatesGraphWith("roles"));
assertThat(colleaguesOfColleagues).terminatesGraphWith("roles");
}
@Test(expected = Exception.class) // DATAJPA-1041, DATAJPA-1075
@@ -144,4 +162,181 @@ public class Jpa21UtilsTests {
Jpa21Utils.configureFetchGraphFrom(new JpaEntityGraph("name", EntityGraphType.FETCH, new String[] { "¯\\_(ツ)_/¯" }),
em.createEntityGraph(User.class));
}
/**
* Lookup the {@link AttributeNode} with given {@literal nodeName} in the root of the given {@literal graph}.
*
* @param nodeName
* @param graph
* @return
*/
public static @Nullable AttributeNode<?> findNode(String nodeName, @Nullable EntityGraph<?> graph) {
if (graph == null) {
return null;
}
return findNode(nodeName, graph.getAttributeNodes());
}
/**
* Lookup the {@link AttributeNode} with given {@literal nodeName} in the {@link List} of given {@literal nodes}.
*
* @param nodeName
* @param nodes
* @return
*/
@Nullable
public static AttributeNode<?> findNode(String nodeName, List<AttributeNode<?>> nodes) {
if (CollectionUtils.isEmpty(nodes)) {
return null;
}
for (AttributeNode<?> node : nodes) {
if (ObjectUtils.nullSafeEquals(node.getAttributeName(), nodeName)) {
return node;
}
}
return null;
}
/**
* Lookup the {@link AttributeNode} with given {@literal nodeName} in the first {@link Subgraph} of the given
* {@literal node}.
*
* @param attributeName
* @param node
* @return
*/
@Nullable
public static AttributeNode<?> findNode(String attributeName, AttributeNode<?> node) {
if (CollectionUtils.isEmpty(node.getSubgraphs())) {
return null;
}
Subgraph<?> subgraph = node.getSubgraphs().values().iterator().next();
return findNode(attributeName, subgraph.getAttributeNodes());
}
static <T> AttributeNodeAssert<T> assertThat(AttributeNode<T> actual) {
return new AttributeNodeAssert<>(actual);
}
static class AttributeNodeAssert<T> extends AbstractAssert<AttributeNodeAssert<T>, AttributeNode<T>> {
private final AttributeNode<T> attributeNode;
AttributeNodeAssert(AttributeNode<T> attributeNode) {
super(attributeNode, AttributeNodeAssert.class);
this.attributeNode = attributeNode;
}
AttributeNodeAssert<T> terminatesGraph() {
Assertions.assertThat(CollectionUtils.isEmpty(attributeNode.getSubgraphs()))
.describedAs(String.format("'%s' was expected to be a terminating node but has subgraphs %s.",
attributeNode.getAttributeName(), extractSubgraphsAttributeNames()))
.isTrue();
return this;
}
AttributeNodeAssert<T> terminatesGraphWith(String... nodeNames) {
List<String> nodes = Arrays.asList(nodeNames);
Assertions.assertThat(attributeNode.getSubgraphs()) //
.describedAs(
String.format("Leaf properties %s could not be found. The node does not have any subgraphs.", nodes)) //
.isNotNull() //
.isNotEmpty();
Subgraph<?> graph = attributeNode.getSubgraphs().values().iterator().next();
SoftAssertions.assertSoftly(softly -> {
for (String nodeName : nodes) {
AttributeNode<?> node = findNode(nodeName, graph.getAttributeNodes());
String notInSubgraph = String.format(
"AttributeNode '%s' could not be found in subgraph for '%s'. Know nodes are: %s.", nodeName,
attributeNode.getAttributeName(), extractExistingAttributeNames(graph));
softly.assertThat(node).describedAs(notInSubgraph).isNotNull();
String notLeaf = String.format(
"AttributeNode %s of subgraph %s is not a leaf property but has %d SubGraph(s).", nodeName,
attributeNode.getAttributeName(), node.getSubgraphs().size());
softly.assertThat(node.getSubgraphs()) //
.describedAs(notLeaf) //
.isEmpty();
}
});
return this;
}
AttributeNodeAssert<T> hasSubgraphs(String... subgraphNames) {
List<String> subgraphs = Arrays.asList(subgraphNames);
Assertions.assertThat(attributeNode.getSubgraphs()) //
.describedAs(
String.format("Subgraphs %s could not be found. The node does not have any subgraphs.", subgraphs)) //
.isNotNull() //
.isNotEmpty();
Subgraph<?> graph = attributeNode.getSubgraphs().values().iterator().next();
SoftAssertions.assertSoftly(softly -> {
for (String subgraphName : subgraphs) {
AttributeNode<?> node = findNode(subgraphName, graph.getAttributeNodes());
String notFound = String.format("Subgraph '%s' could not be found in SubGraph for '%s'. Known nodes are: %s.",
subgraphName, attributeNode.getAttributeName(), extractExistingAttributeNames(graph));
softly.assertThat(node) //
.describedAs(notFound) //
.isNotNull();
String notSubGraph = String.format("'%s' of SubGraph '%s' is not a SubGraph.", subgraphName,
attributeNode.getAttributeName());
softly.assertThat(node.getSubgraphs()) //
.describedAs(notSubGraph).isNotNull() //
.isNotEmpty();
}
});
return this;
}
private List<String> extractSubgraphsAttributeNames() {
Iterator<Subgraph> iterator = attributeNode.getSubgraphs().values().iterator();
if (!iterator.hasNext()) {
return Collections.emptyList();
}
return extractExistingAttributeNames(iterator.next());
}
private static List<String> extractExistingAttributeNames(Subgraph<?> graph) {
List<String> result = new ArrayList<>(graph.getAttributeNodes().size());
for (AttributeNode<?> node : graph.getAttributeNodes()) {
result.add(node.getAttributeName());
}
return result;
}
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.query;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.lang.reflect.Method;
import java.util.List;
@@ -42,6 +41,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* Integration tests for {@link JpaCountQueryCreator}.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:infrastructure.xml")
@@ -67,7 +67,7 @@ public class JpaCountQueryCreatorIntegrationTests {
TypedQuery<? extends Object> query = entityManager.createQuery(creator.createQuery());
assertThat(HibernateUtils.getHibernateQuery(query), startsWith("select distinct count(distinct"));
assertThat(HibernateUtils.getHibernateQuery(query)).startsWith("select distinct count(distinct");
}
interface SomeRepository extends Repository<User, Long> {

View File

@@ -16,8 +16,7 @@
package org.springframework.data.jpa.repository.query;
import static javax.persistence.TemporalType.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.lang.reflect.Method;
import java.util.Date;
@@ -32,6 +31,7 @@ import org.springframework.data.jpa.repository.query.JpaParameters.JpaParameter;
* Unit tests for {@link JpaParameters}.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
public class JpaParametersUnitTests {
@@ -43,12 +43,12 @@ public class JpaParametersUnitTests {
JpaParameters parameters = new JpaParameters(method);
JpaParameter parameter = parameters.getBindableParameter(0);
assertThat(parameter.isSpecialParameter(), is(false));
assertThat(parameter.isTemporalParameter(), is(true));
assertThat(parameter.getTemporalType(), is(TemporalType.TIMESTAMP));
assertThat(parameter.isSpecialParameter()).isFalse();
assertThat(parameter.isTemporalParameter()).isTrue();
assertThat(parameter.getTemporalType()).isEqualTo(TemporalType.TIMESTAMP);
parameter = parameters.getBindableParameter(1);
assertThat(parameter.isTemporalParameter(), is(false));
assertThat(parameter.isTemporalParameter()).isFalse();
}
interface SampleRepository {

View File

@@ -15,9 +15,8 @@
*/
package org.springframework.data.jpa.repository.query;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import java.util.Arrays;
@@ -60,8 +59,10 @@ public class JpaQueryExecutionUnitTests {
@Mock TypedQuery<Long> countQuery;
public static void sampleMethod(Pageable pageable) {}
@Before
public void setUp(){
public void setUp() {
when(query.executeUpdate()).thenReturn(0);
when(jpaQuery.createQuery(Mockito.any(Object[].class))).thenReturn(query);
@@ -90,7 +91,7 @@ public class JpaQueryExecutionUnitTests {
return null;
}
}.execute(jpaQuery, new Object[] {}), is(nullValue()));
}.execute(jpaQuery, new Object[] {})).isNull();
}
@Test // DATAJPA-806
@@ -241,11 +242,9 @@ public class JpaQueryExecutionUnitTests {
Object result = execution.execute(jpaQuery, new Object[0]);
assertThat(result, is(instanceOf(String.class)));
assertThat(result).isInstanceOf(String.class);
}
public static void sampleMethod(Pageable pageable) {}
static class StubQueryExecution extends JpaQueryExecution {
@Override

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.query;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@@ -62,6 +61,7 @@ import org.springframework.data.repository.query.QueryMethod;
* @author Oliver Gierke
* @author Thomas Darimont
* @author Christoph Strobl
* @author Jens Schauder
*/
@RunWith(MockitoJUnitRunner.class)
public class JpaQueryMethodUnitTests {
@@ -102,10 +102,10 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = getQueryMethod(UserRepository.class, "findByLastname", String.class);
assertEquals("User.findByLastname", method.getNamedQueryName());
assertThat(method.isCollectionQuery(), is(true));
assertThat(method.getAnnotatedQuery(), is(nullValue()));
assertThat(method.isNativeQuery(), is(false));
assertThat(method.getNamedQueryName()).isEqualTo("User.findByLastname");
assertThat(method.isCollectionQuery()).isTrue();
assertThat(method.getAnnotatedQuery()).isNull();
assertThat(method.isNativeQuery()).isFalse();
}
@Test(expected = IllegalArgumentException.class)
@@ -125,17 +125,17 @@ public class JpaQueryMethodUnitTests {
public void returnsCorrectName() throws Exception {
JpaQueryMethod method = getQueryMethod(UserRepository.class, "findByLastname", String.class);
assertThat(method.getName(), is("findByLastname"));
assertThat(method.getName()).isEqualTo("findByLastname");
}
@Test
public void returnsQueryIfAvailable() throws Exception {
JpaQueryMethod method = getQueryMethod(UserRepository.class, "findByLastname", String.class);
assertThat(method.getAnnotatedQuery(), is(nullValue()));
assertThat(method.getAnnotatedQuery()).isNull();
method = getQueryMethod(UserRepository.class, "findByAnnotatedQuery", String.class);
assertThat(method.getAnnotatedQuery(), is(notNullValue()));
assertThat(method.getAnnotatedQuery()).isNotNull();
}
@Test(expected = IllegalStateException.class)
@@ -166,7 +166,7 @@ public class JpaQueryMethodUnitTests {
public void recognizesModifyingMethod() throws Exception {
JpaQueryMethod method = getQueryMethod(UserRepository.class, "renameAllUsersTo", String.class);
assertTrue(method.isModifyingQuery());
assertThat(method.isModifyingQuery()).isTrue();
}
@Test(expected = IllegalArgumentException.class)
@@ -191,9 +191,9 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = getQueryMethod(UserRepository.class, "findByLastname", String.class);
List<QueryHint> hints = method.getHints();
assertNotNull(hints);
assertThat(hints.get(0).name(), is("foo"));
assertThat(hints.get(0).value(), is("bar"));
assertThat(hints).isNotNull();
assertThat(hints.get(0).name()).isEqualTo("foo");
assertThat(hints.get(0).value()).isEqualTo("bar");
}
private JpaQueryMethod getQueryMethod(Class<?> repositoryInterface, String methodName, Class<?>... parameterTypes)
@@ -210,29 +210,29 @@ public class JpaQueryMethodUnitTests {
RepositoryMetadata metadata = new DefaultRepositoryMetadata(UserRepository.class);
JpaQueryMethod queryMethod = getQueryMethod(UserRepository.class, "findByLastname", String.class);
assertThat(queryMethod.getNamedQueryName(), is("User.findByLastname"));
assertThat(queryMethod.getNamedQueryName()).isEqualTo("User.findByLastname");
Method method = UserRepository.class.getMethod("renameAllUsersTo", String.class);
queryMethod = new JpaQueryMethod(method, metadata, factory, extractor);
assertThat(queryMethod.getNamedQueryName(), is("User.renameAllUsersTo"));
assertThat(queryMethod.getNamedQueryName()).isEqualTo("User.renameAllUsersTo");
method = UserRepository.class.getMethod("findSpecialUsersByLastname", String.class);
queryMethod = new JpaQueryMethod(method, metadata, factory, extractor);
assertThat(queryMethod.getNamedQueryName(), is("SpecialUser.findSpecialUsersByLastname"));
assertThat(queryMethod.getNamedQueryName()).isEqualTo("SpecialUser.findSpecialUsersByLastname");
}
@Test // DATAJPA-117
public void discoversNativeQuery() throws Exception {
JpaQueryMethod method = getQueryMethod(ValidRepository.class, "findByLastname", String.class);
assertThat(method.isNativeQuery(), is(true));
assertThat(method.isNativeQuery()).isTrue();
}
@Test // DATAJPA-129
public void considersAnnotatedNamedQueryName() throws Exception {
JpaQueryMethod queryMethod = getQueryMethod(ValidRepository.class, "findByNamedQuery");
assertThat(queryMethod.getNamedQueryName(), is("HateoasAwareSpringDataWebConfiguration.bar"));
assertThat(queryMethod.getNamedQueryName()).isEqualTo("HateoasAwareSpringDataWebConfiguration.bar");
}
@Test // DATAJPA-73
@@ -241,37 +241,35 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = getQueryMethod(ValidRepository.class, "findOneLocked", Integer.class);
LockModeType lockMode = method.getLockModeType();
assertEquals(LockModeType.PESSIMISTIC_WRITE, lockMode);
assertThat(lockMode).isEqualTo(LockModeType.PESSIMISTIC_WRITE);
}
@Test // DATAJPA-142
public void returnsDefaultCountQueryName() throws Exception {
JpaQueryMethod method = getQueryMethod(UserRepository.class, "findByLastname", String.class);
assertThat(method.getNamedCountQueryName(), is("User.findByLastname.count"));
assertThat(method.getNamedCountQueryName()).isEqualTo("User.findByLastname.count");
}
@Test // DATAJPA-142
public void returnsDefaultCountQueryNameBasedOnConfiguredNamedQueryName() throws Exception {
JpaQueryMethod method = getQueryMethod(ValidRepository.class, "findByNamedQuery");
assertThat(method.getNamedCountQueryName(), is("HateoasAwareSpringDataWebConfiguration.bar.count"));
assertThat(method.getNamedCountQueryName()).isEqualTo("HateoasAwareSpringDataWebConfiguration.bar.count");
}
@Test // DATAJPA-185
public void rejectsInvalidNamedParameter() throws Exception {
try {
getQueryMethod(InvalidRepository.class, "findByAnnotatedQuery", String.class);
fail();
} catch (IllegalStateException e) {
// Parameter from query
assertThat(e.getMessage(), containsString("foo"));
// Parameter name from annotation
assertThat(e.getMessage(), containsString("param"));
// Method name
assertThat(e.getMessage(), containsString("findByAnnotatedQuery"));
}
assertThatThrownBy(() -> getQueryMethod(InvalidRepository.class, "findByAnnotatedQuery", String.class))
.isInstanceOf(IllegalStateException.class)
// Parameter from query
.hasMessageContaining("foo")
// Parameter name from annotation
.hasMessageContaining("param")
// Method name
.hasMessageContaining("findByAnnotatedQuery");
}
@Test // DATAJPA-207
@@ -282,8 +280,8 @@ public class JpaQueryMethodUnitTests {
when(metadata.getReturnedDomainClass(findsProjections)).thenReturn((Class) Integer.class);
when(metadata.getReturnedDomainClass(findsProjection)).thenReturn((Class) Integer.class);
assertThat(new JpaQueryMethod(findsProjections, metadata, factory, extractor).isQueryForEntity(), is(false));
assertThat(new JpaQueryMethod(findsProjection, metadata, factory, extractor).isQueryForEntity(), is(false));
assertThat(new JpaQueryMethod(findsProjections, metadata, factory, extractor).isQueryForEntity()).isFalse();
assertThat(new JpaQueryMethod(findsProjection, metadata, factory, extractor).isQueryForEntity()).isFalse();
}
@Test // DATAJPA-345
@@ -291,10 +289,10 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = getQueryMethod(ValidRepository.class, "withMetaAnnotation");
assertThat(method.getLockModeType(), is(LockModeType.OPTIMISTIC_FORCE_INCREMENT));
assertThat(method.getHints(), hasSize(1));
assertThat(method.getHints().get(0).name(), is("foo"));
assertThat(method.getHints().get(0).value(), is("bar"));
assertThat(method.getLockModeType()).isEqualTo(LockModeType.OPTIMISTIC_FORCE_INCREMENT);
assertThat(method.getHints()).hasSize(1);
assertThat(method.getHints().get(0).name()).isEqualTo("foo");
assertThat(method.getHints().get(0).value()).isEqualTo("bar");
}
@Test // DATAJPA-466
@@ -305,9 +303,9 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = new JpaQueryMethod(queryMethodWithCustomEntityFetchGraph, metadata, factory, extractor);
assertThat(method.getEntityGraph(), is(notNullValue()));
assertThat(method.getEntityGraph().getName(), is("User.propertyLoadPath"));
assertThat(method.getEntityGraph().getType(), is(EntityGraphType.LOAD));
assertThat(method.getEntityGraph()).isNotNull();
assertThat(method.getEntityGraph().getName()).isEqualTo("User.propertyLoadPath");
assertThat(method.getEntityGraph().getType()).isEqualTo(EntityGraphType.LOAD);
}
@Test // DATAJPA-612
@@ -319,9 +317,9 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = new JpaQueryMethod(JpaRepositoryOverride.class.getMethod("findAll"), metadata, factory,
extractor);
assertThat(method.getEntityGraph(), is(notNullValue()));
assertThat(method.getEntityGraph().getName(), is("User.detail"));
assertThat(method.getEntityGraph().getType(), is(EntityGraphType.FETCH));
assertThat(method.getEntityGraph()).isNotNull();
assertThat(method.getEntityGraph().getName()).isEqualTo("User.detail");
assertThat(method.getEntityGraph().getType()).isEqualTo(EntityGraphType.FETCH);
}
@Test // DATAJPA-689
@@ -333,9 +331,9 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = new JpaQueryMethod(JpaRepositoryOverride.class.getMethod("findOne", Long.class), metadata,
factory, extractor);
assertThat(method.getEntityGraph(), is(notNullValue()));
assertThat(method.getEntityGraph().getName(), is("User.detail"));
assertThat(method.getEntityGraph().getType(), is(EntityGraphType.FETCH));
assertThat(method.getEntityGraph()).isNotNull();
assertThat(method.getEntityGraph().getName()).isEqualTo("User.detail");
assertThat(method.getEntityGraph().getType()).isEqualTo(EntityGraphType.FETCH);
}
/**
@@ -350,9 +348,9 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = new JpaQueryMethod(JpaRepositoryOverride.class.getMethod("getOneById", Long.class),
metadata, factory, extractor);
assertThat(method.getEntityGraph(), is(notNullValue()));
assertThat(method.getEntityGraph().getName(), is("User.getOneById"));
assertThat(method.getEntityGraph().getType(), is(EntityGraphType.FETCH));
assertThat(method.getEntityGraph()).isNotNull();
assertThat(method.getEntityGraph().getName()).isEqualTo("User.getOneById");
assertThat(method.getEntityGraph().getType()).isEqualTo(EntityGraphType.FETCH);
}
@Test // DATAJPA-758
@@ -365,7 +363,7 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = getQueryMethod(ValidRepository.class, "withMetaAnnotationUsingAliasFor");
assertThat(method.getLockModeType(), is(LockModeType.PESSIMISTIC_FORCE_INCREMENT));
assertThat(method.getLockModeType()).isEqualTo(LockModeType.PESSIMISTIC_FORCE_INCREMENT);
}
@Test // DATAJPA-871
@@ -373,9 +371,9 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = getQueryMethod(ValidRepository.class, "withMetaAnnotationUsingAliasFor");
assertThat(method.getHints(), hasSize(1));
assertThat(method.getHints().get(0).name(), is("foo"));
assertThat(method.getHints().get(0).value(), is("bar"));
assertThat(method.getHints()).hasSize(1);
assertThat(method.getHints().get(0).name()).isEqualTo("foo");
assertThat(method.getHints().get(0).value()).isEqualTo("bar");
}
@@ -384,7 +382,7 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = getQueryMethod(ValidRepository.class, "withMetaAnnotationUsingAliasFor");
assertThat(method.applyHintsToCountQuery(), is(true));
assertThat(method.applyHintsToCountQuery()).isTrue();
}
@Test // DATAJPA-871
@@ -392,8 +390,8 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = getQueryMethod(ValidRepository.class, "withMetaAnnotationUsingAliasFor");
assertThat(method.isModifyingQuery(), is(true));
assertThat(method.getClearAutomatically(), is(true));
assertThat(method.isModifyingQuery()).isTrue();
assertThat(method.getClearAutomatically()).isTrue();
}
@Test // DATAJPA-871
@@ -401,7 +399,7 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = getQueryMethod(ValidRepository.class, "withMetaAnnotationUsingAliasFor");
assertThat(method.applyHintsToCountQuery(), is(true));
assertThat(method.applyHintsToCountQuery()).isTrue();
}
@Test // DATAJPA-871
@@ -409,7 +407,7 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = getQueryMethod(ValidRepository.class, "withMetaAnnotationUsingAliasFor");
assertThat(method.getAnnotatedQuery(), is(equalTo("select u from User u where u.firstname = ?1")));
assertThat(method.getAnnotatedQuery()).isEqualTo("select u from User u where u.firstname = ?1");
}
@Test // DATAJPA-871
@@ -417,7 +415,7 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = getQueryMethod(ValidRepository.class, "withMetaAnnotationUsingAliasFor");
assertThat(method.getCountQuery(), is(equalTo("select u from User u where u.lastname = ?1")));
assertThat(method.getCountQuery()).isEqualTo("select u from User u where u.lastname = ?1");
}
@Test // DATAJPA-871
@@ -425,7 +423,7 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = getQueryMethod(ValidRepository.class, "withMetaAnnotationUsingAliasFor");
assertThat(method.getCountQueryProjection(), is(equalTo("foo-bar")));
assertThat(method.getCountQueryProjection()).isEqualTo("foo-bar");
}
@Test // DATAJPA-871
@@ -433,7 +431,7 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = getQueryMethod(ValidRepository.class, "withMetaAnnotationUsingAliasFor");
assertThat(method.getNamedQueryName(), is(equalTo("namedQueryName")));
assertThat(method.getNamedQueryName()).isEqualTo("namedQueryName");
}
@Test // DATAJPA-871
@@ -441,7 +439,7 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = getQueryMethod(ValidRepository.class, "withMetaAnnotationUsingAliasFor");
assertThat(method.getNamedCountQueryName(), is(equalTo("namedCountQueryName")));
assertThat(method.getNamedCountQueryName()).isEqualTo("namedCountQueryName");
}
@Test // DATAJPA-871
@@ -449,7 +447,7 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = getQueryMethod(ValidRepository.class, "withMetaAnnotationUsingAliasFor");
assertThat(method.isNativeQuery(), is(true));
assertThat(method.isNativeQuery()).isTrue();
}
@Test // DATAJPA-871
@@ -461,9 +459,9 @@ public class JpaQueryMethodUnitTests {
JpaQueryMethod method = new JpaQueryMethod(
JpaRepositoryOverride.class.getMethod("getOneWithCustomEntityGraphAnnotation"), metadata, factory, extractor);
assertThat(method.getEntityGraph(), is(notNullValue()));
assertThat(method.getEntityGraph().getName(), is("User.detail"));
assertThat(method.getEntityGraph().getType(), is(EntityGraphType.LOAD));
assertThat(method.getEntityGraph()).isNotNull();
assertThat(method.getEntityGraph().getName()).isEqualTo("User.detail");
assertThat(method.getEntityGraph().getType()).isEqualTo(EntityGraphType.LOAD);
}
/**
@@ -597,8 +595,7 @@ public class JpaQueryMethodUnitTests {
LockModeType lock() default LockModeType.PESSIMISTIC_FORCE_INCREMENT;
@AliasFor(annotation = QueryHints.class, attribute = "value")
QueryHint[] hints() default @QueryHint(name = "foo", value = "bar")
;
QueryHint[] hints() default @QueryHint(name = "foo", value = "bar");
@AliasFor(annotation = QueryHints.class, attribute = "forCounting")
boolean doCount() default true;

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.query;
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.jpa.repository.query.StringQuery.LikeParameterBinding;
@@ -27,9 +26,16 @@ import org.springframework.data.repository.query.parser.Part.Type;
*
* @author Oliver Gierke
* @author Thomas Darimont
* @author Jens Schauder
*/
public class LikeBindingUnitTests {
private static void assertAugmentedValue(Type type, Object value) {
LikeParameterBinding binding = new LikeParameterBinding("foo", type);
assertThat(binding.prepare("value")).isEqualTo(value);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullName() {
new LikeParameterBinding(null, Type.CONTAINING);
@@ -60,11 +66,11 @@ public class LikeBindingUnitTests {
LikeParameterBinding binding = new LikeParameterBinding("foo", Type.CONTAINING);
assertThat(binding.hasName("foo"), is(true));
assertThat(binding.hasName("bar"), is(false));
assertThat(binding.hasName(null), is(false));
assertThat(binding.hasPosition(0), is(false));
assertThat(binding.getType(), is(Type.CONTAINING));
assertThat(binding.hasName("foo")).isTrue();
assertThat(binding.hasName("bar")).isFalse();
assertThat(binding.hasName(null)).isFalse();
assertThat(binding.hasPosition(0)).isFalse();
assertThat(binding.getType()).isEqualTo(Type.CONTAINING);
}
@Test
@@ -72,11 +78,11 @@ public class LikeBindingUnitTests {
LikeParameterBinding binding = new LikeParameterBinding(1, Type.CONTAINING);
assertThat(binding.hasName("foo"), is(false));
assertThat(binding.hasName(null), is(false));
assertThat(binding.hasPosition(0), is(false));
assertThat(binding.hasPosition(1), is(true));
assertThat(binding.getType(), is(Type.CONTAINING));
assertThat(binding.hasName("foo")).isFalse();
assertThat(binding.hasName(null)).isFalse();
assertThat(binding.hasPosition(0)).isFalse();
assertThat(binding.hasPosition(1)).isTrue();
assertThat(binding.getType()).isEqualTo(Type.CONTAINING);
}
@Test
@@ -86,12 +92,6 @@ public class LikeBindingUnitTests {
assertAugmentedValue(Type.ENDING_WITH, "%value");
assertAugmentedValue(Type.STARTING_WITH, "value%");
assertThat(new LikeParameterBinding(1, Type.CONTAINING).prepare(null), is(nullValue()));
}
private static void assertAugmentedValue(Type type, Object value) {
LikeParameterBinding binding = new LikeParameterBinding("foo", type);
assertThat(binding.prepare("value"), is(value));
assertThat(new LikeParameterBinding(1, Type.CONTAINING).prepare(null)).isNull();
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.query;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.lang.reflect.Method;
@@ -40,6 +39,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* Integration tests for {@link ParameterMetadataProvider}.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:infrastructure.xml")
@@ -58,9 +58,10 @@ public class ParameterExpressionProviderTests {
CriteriaBuilder builder = em.getCriteriaBuilder();
PersistenceProvider persistenceProvider = PersistenceProvider.fromEntityManager(em);
ParameterMetadataProvider provider = new ParameterMetadataProvider(builder, accessor, persistenceProvider, EscapeCharacter.DEFAULT);
ParameterMetadataProvider provider = new ParameterMetadataProvider(builder, accessor, persistenceProvider,
EscapeCharacter.DEFAULT);
ParameterExpression<? extends Comparable> expression = provider.next(part, Comparable.class).getExpression();
assertThat(expression.getParameterType(), is(typeCompatibleWith(int.class)));
assertThat(expression.getParameterType()).isEqualTo(int.class);
}
interface SampleRepository {

View File

@@ -15,15 +15,12 @@
*/
package org.springframework.data.jpa.repository.query;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.jpa.repository.query.QueryUtils.*;
import java.util.Collections;
import java.util.Set;
import org.hamcrest.Matcher;
import org.junit.Test;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.domain.Sort;
@@ -51,8 +48,6 @@ public class QueryUtilsUnitTests {
static final String QUERY_WITH_AS = "select u from User as u where u.username = ?";
static final Matcher<String> IS_U = is("u");
@Test
public void createsCountQueryCorrectly() throws Exception {
assertCountQuery(QUERY, COUNT_QUERY);
@@ -109,20 +104,20 @@ public class QueryUtilsUnitTests {
@Test
public void detectsAliasCorrectly() throws Exception {
assertThat(detectAlias(QUERY), IS_U);
assertThat(detectAlias(SIMPLE_QUERY), IS_U);
assertThat(detectAlias(COUNT_QUERY), IS_U);
assertThat(detectAlias(QUERY_WITH_AS), IS_U);
assertThat(detectAlias("SELECT FROM USER U"), is("U"));
assertThat(detectAlias("select u from User u"), IS_U);
assertThat(detectAlias("select u from com.acme.User u"), IS_U);
assertThat(detectAlias("select u from T05User u"), IS_U);
assertThat(detectAlias(QUERY)).isEqualTo("u");
assertThat(detectAlias(SIMPLE_QUERY)).isEqualTo("u");
assertThat(detectAlias(COUNT_QUERY)).isEqualTo("u");
assertThat(detectAlias(QUERY_WITH_AS)).isEqualTo("u");
assertThat(detectAlias("SELECT FROM USER U")).isEqualTo("U");
assertThat(detectAlias("select u from User u")).isEqualTo("u");
assertThat(detectAlias("select u from com.acme.User u")).isEqualTo("u");
assertThat(detectAlias("select u from T05User u")).isEqualTo("u");
}
@Test
public void allowsFullyQualifiedEntityNamesInQuery() {
assertThat(detectAlias(FQ_QUERY), IS_U);
assertThat(detectAlias(FQ_QUERY)).isEqualTo("u");
assertCountQuery(FQ_QUERY, "select count(u) from org.acme.domain.User$Foo_Bar u");
}
@@ -130,38 +125,38 @@ public class QueryUtilsUnitTests {
public void detectsJoinAliasesCorrectly() {
Set<String> aliases = getOuterJoinAliases("select p from Person p left outer join x.foo b2_$ar where …");
assertThat(aliases, hasSize(1));
assertThat(aliases, hasItems("b2_$ar"));
assertThat(aliases).hasSize(1);
assertThat(aliases).contains("b2_$ar");
aliases = getOuterJoinAliases("select p from Person p left join x.foo b2_$ar where …");
assertThat(aliases, hasSize(1));
assertThat(aliases, hasItems("b2_$ar"));
assertThat(aliases).hasSize(1);
assertThat(aliases).contains("b2_$ar");
aliases = getOuterJoinAliases(
"select p from Person p left outer join x.foo as b2_$ar, left join x.bar as foo where …");
assertThat(aliases, hasSize(2));
assertThat(aliases, hasItems("b2_$ar", "foo"));
assertThat(aliases).hasSize(2);
assertThat(aliases).contains("b2_$ar", "foo");
aliases = getOuterJoinAliases(
"select p from Person p left join x.foo as b2_$ar, left outer join x.bar foo where …");
assertThat(aliases, hasSize(2));
assertThat(aliases, hasItems("b2_$ar", "foo"));
assertThat(aliases).hasSize(2);
assertThat(aliases).contains("b2_$ar", "foo");
}
@Test // DATAJPA-252
public void doesNotPrefixOrderReferenceIfOuterJoinAliasDetected() {
String query = "select p from Person p left join p.address address";
assertThat(applySorting(query, Sort.by("address.city")), endsWith("order by address.city asc"));
assertThat(applySorting(query, Sort.by("address.city", "lastname"), "p"),
endsWith("order by address.city asc, p.lastname asc"));
assertThat(applySorting(query, Sort.by("address.city"))).endsWith("order by address.city asc");
assertThat(applySorting(query, Sort.by("address.city", "lastname"), "p"))
.endsWith("order by address.city asc, p.lastname asc");
}
@Test // DATAJPA-252
public void extendsExistingOrderByClausesCorrectly() {
String query = "select p from Person p order by p.lastname asc";
assertThat(applySorting(query, Sort.by("firstname"), "p"), endsWith("order by p.lastname asc, p.firstname asc"));
assertThat(applySorting(query, Sort.by("firstname"), "p")).endsWith("order by p.lastname asc, p.firstname asc");
}
@Test // DATAJPA-296
@@ -170,7 +165,7 @@ public class QueryUtilsUnitTests {
Sort sort = Sort.by(Order.by("firstname").ignoreCase());
String query = "select p from Person p";
assertThat(applySorting(query, sort, "p"), endsWith("order by lower(p.firstname) asc"));
assertThat(applySorting(query, sort, "p")).endsWith("order by lower(p.firstname) asc");
}
@Test // DATAJPA-296
@@ -179,7 +174,7 @@ public class QueryUtilsUnitTests {
Sort sort = Sort.by(Order.by("firstname").ignoreCase());
String query = "select p from Person p order by p.lastname asc";
assertThat(applySorting(query, sort, "p"), endsWith("order by p.lastname asc, lower(p.firstname) asc"));
assertThat(applySorting(query, sort, "p")).endsWith("order by p.lastname asc, lower(p.firstname) asc");
}
@Test // DATAJPA-342
@@ -200,7 +195,7 @@ public class QueryUtilsUnitTests {
public void doesNotPrefixSortsIfFunction() {
Sort sort = Sort.by("sum(foo)");
assertThat(applySorting("select p from Person p", sort, "p"), endsWith("order by sum(foo) asc"));
assertThat(applySorting("select p from Person p", sort, "p")).endsWith("order by sum(foo) asc");
}
@Test // DATAJPA-377
@@ -215,7 +210,7 @@ public class QueryUtilsUnitTests {
Sort sort = Sort.by("lastname");
String query = applySorting("select p from Person p ORDER BY p.firstname", sort, "p");
assertThat(query, endsWith("ORDER BY p.firstname, p.lastname asc"));
assertThat(query).endsWith("ORDER BY p.firstname, p.lastname asc");
}
@Test // DATAJPA-409
@@ -230,8 +225,8 @@ public class QueryUtilsUnitTests {
@Test // DATAJPA-456
public void createCountQueryFromTheGivenCountProjection() {
assertThat(createCountQueryFor("select p.lastname,p.firstname from Person p", "p.lastname"),
is("select count(p.lastname) from Person p"));
assertThat(createCountQueryFor("select p.lastname,p.firstname from Person p", "p.lastname"))
.isEqualTo("select count(p.lastname) from Person p");
}
@Test // DATAJPA-726
@@ -240,17 +235,17 @@ public class QueryUtilsUnitTests {
String query = "select p from Customer c join c.productOrder p where p.delayed = true";
Sort sort = Sort.by("p.lineItems");
assertThat(applySorting(query, sort, "c"), endsWith("order by p.lineItems asc"));
assertThat(applySorting(query, sort, "c")).endsWith("order by p.lineItems asc");
}
@Test // DATAJPA-736
public void supportsNonAsciiCharactersInEntityNames() {
assertThat(createCountQueryFor("select u from Usèr u"), is("select count(u) from Usèr u"));
assertThat(createCountQueryFor("select u from Usèr u")).isEqualTo("select count(u) from Usèr u");
}
@Test // DATAJPA-798
public void detectsAliasInQueryContainingLineBreaks() {
assertThat(detectAlias("select \n u \n from \n User \nu"), is("u"));
assertThat(detectAlias("select \n u \n from \n User \nu")).isEqualTo("u");
}
@Test // DATAJPA-815
@@ -259,12 +254,12 @@ public class QueryUtilsUnitTests {
String query = "from Cat c join Dog d";
Sort sort = Sort.by("dPropertyStartingWithJoinAlias");
assertThat(applySorting(query, sort, "c"), endsWith("order by c.dPropertyStartingWithJoinAlias asc"));
assertThat(applySorting(query, sort, "c")).endsWith("order by c.dPropertyStartingWithJoinAlias asc");
}
@Test // DATAJPA-938
public void detectsConstructorExpressionInDistinctQuery() {
assertThat(hasConstructorExpression("select distinct new Foo() from Bar b"), is(true));
assertThat(hasConstructorExpression("select distinct new Foo() from Bar b")).isTrue();
}
@Test // DATAJPA-938
@@ -274,17 +269,17 @@ public class QueryUtilsUnitTests {
+ "from Bar lp join lp.investmentProduct ip " //
+ "where (lp.toDate is null and lp.fromDate <= :now and lp.fromDate is not null) and lp.accountId = :accountId " //
+ "group by ip.id, ip.name, lp.accountId " //
+ "order by ip.name ASC"), is(true));
+ "order by ip.name ASC")).isTrue();
}
@Test // DATAJPA-938
public void detectsConstructorExpressionWithLineBreaks() {
assertThat(hasConstructorExpression("select new foo.bar.FooBar(\na.id) from DtoA a "), is(true));
assertThat(hasConstructorExpression("select new foo.bar.FooBar(\na.id) from DtoA a ")).isTrue();
}
@Test // DATAJPA-960
public void doesNotQualifySortIfNoAliasDetected() {
assertThat(applySorting("from mytable where ?1 is null", Sort.by("firstname")), endsWith("order by firstname asc"));
assertThat(applySorting("from mytable where ?1 is null", Sort.by("firstname"))).endsWith("order by firstname asc");
}
@Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-965, DATAJPA-970
@@ -298,7 +293,7 @@ public class QueryUtilsUnitTests {
public void doesNotPrefixUnsageJpaSortFunctionCalls() {
JpaSort sort = JpaSort.unsafe("sum(foo)");
assertThat(applySorting("select p from Person p", sort, "p"), endsWith("order by sum(foo) asc"));
assertThat(applySorting("select p from Person p", sort, "p")).endsWith("order by sum(foo) asc");
}
@Test // DATAJPA-965, DATAJPA-970
@@ -307,7 +302,7 @@ public class QueryUtilsUnitTests {
String query = "SELECT AVG(m.price) AS avgPrice, SUM(m.stocks) AS sumStocks FROM Magazine m";
Sort sort = Sort.by("avgPrice", "sumStocks");
assertThat(applySorting(query, sort, "m"), endsWith("order by avgPrice asc, sumStocks asc"));
assertThat(applySorting(query, sort, "m")).endsWith("order by avgPrice asc, sumStocks asc");
}
@Test // DATAJPA-965, DATAJPA-970
@@ -316,7 +311,7 @@ public class QueryUtilsUnitTests {
String query = "SELECT AVG(m.price) AS avgPrice FROM Magazine m";
Sort sort = Sort.by("avgPrice");
assertThat(applySorting(query, sort, "m"), endsWith("order by avgPrice asc"));
assertThat(applySorting(query, sort, "m")).endsWith("order by avgPrice asc");
}
@Test // DATAJPA-965, DATAJPA-970
@@ -325,7 +320,7 @@ public class QueryUtilsUnitTests {
String query = "SELECT AVG(m.price) AS avgPrice FROM Magazine m";
Sort sort = Sort.by("someOtherProperty");
assertThat(applySorting(query, sort, "m"), endsWith("order by m.someOtherProperty asc"));
assertThat(applySorting(query, sort, "m")).endsWith("order by m.someOtherProperty asc");
}
@Test // DATAJPA-965, DATAJPA-970
@@ -334,7 +329,7 @@ public class QueryUtilsUnitTests {
String query = "SELECT m.name, AVG(m.price) AS avgPrice FROM Magazine m";
Sort sort = Sort.by("name", "avgPrice");
assertThat(applySorting(query, sort, "m"), endsWith("order by m.name asc, avgPrice asc"));
assertThat(applySorting(query, sort, "m")).endsWith("order by m.name asc, avgPrice asc");
}
@Test // DATAJPA-965, DATAJPA-970
@@ -343,7 +338,7 @@ public class QueryUtilsUnitTests {
String query = "SELECT SUBSTRING(m.name, 2, 5) AS trimmedName FROM Magazine m";
Sort sort = Sort.by("trimmedName");
assertThat(applySorting(query, sort, "m"), endsWith("order by trimmedName asc"));
assertThat(applySorting(query, sort, "m")).endsWith("order by trimmedName asc");
}
@Test // DATAJPA-965, DATAJPA-970
@@ -352,7 +347,7 @@ public class QueryUtilsUnitTests {
String query = "SELECT CONCAT(m.name, 'foo') AS extendedName FROM Magazine m";
Sort sort = Sort.by("extendedName");
assertThat(applySorting(query, sort, "m"), endsWith("order by extendedName asc"));
assertThat(applySorting(query, sort, "m")).endsWith("order by extendedName asc");
}
@Test // DATAJPA-965, DATAJPA-970
@@ -361,7 +356,7 @@ public class QueryUtilsUnitTests {
String query = "SELECT AVG(m.price) AS avg_price FROM Magazine m";
Sort sort = Sort.by("avg_price");
assertThat(applySorting(query, sort, "m"), endsWith("order by avg_price asc"));
assertThat(applySorting(query, sort, "m")).endsWith("order by avg_price asc");
}
@Test // DATAJPA-965, DATAJPA-970
@@ -370,7 +365,7 @@ public class QueryUtilsUnitTests {
String query = "SELECT AVG(m.price) AS m.avg FROM Magazine m";
Sort sort = Sort.by("m.avg");
assertThat(applySorting(query, sort, "m"), endsWith("order by m.avg asc"));
assertThat(applySorting(query, sort, "m")).endsWith("order by m.avg asc");
}
@Test // DATAJPA-965, DATAJPA-970
@@ -379,7 +374,7 @@ public class QueryUtilsUnitTests {
String query = "SELECT AVG( m.price ) AS avgPrice FROM Magazine m";
Sort sort = Sort.by("avgPrice");
assertThat(applySorting(query, sort, "m"), endsWith("order by avgPrice asc"));
assertThat(applySorting(query, sort, "m")).endsWith("order by avgPrice asc");
}
@Test // DATAJPA-1000
@@ -388,7 +383,7 @@ public class QueryUtilsUnitTests {
Set<String> aliases = QueryUtils
.getOuterJoinAliases("SELECT DISTINCT user FROM User user LEFT JOIN FETCH user.authorities AS authority");
assertThat(aliases, contains("authority"));
assertThat(aliases).containsExactly("authority");
}
@Test // DATAJPA-1171
@@ -419,22 +414,20 @@ public class QueryUtilsUnitTests {
public void createCountQuerySupportsWhitespaceCharacters() {
assertThat(createCountQueryFor("select * from User user\n" + //
" where user.age = 18\n" + //
" order by user.name\n "), //
is("select count(user) from User user\n" + //
" where user.age = 18\n "));
" where user.age = 18\n" + //
" order by user.name\n ")).isEqualTo("select count(user) from User user\n" + //
" where user.age = 18\n ");
}
@Test
public void createCountQuerySupportsLineBreaksInSelectClause() {
assertThat(createCountQueryFor("select user.age,\n" + //
" user.name\n" + //
" from User user\n" + //
" where user.age = 18\n" + //
" order\nby\nuser.name\n "), //
is("select count(user) from User user\n" + //
" where user.age = 18\n "));
" user.name\n" + //
" from User user\n" + //
" where user.age = 18\n" + //
" order\nby\nuser.name\n ")).isEqualTo("select count(user) from User user\n" + //
" where user.age = 18\n ");
}
@Test // DATAJPA-1061
@@ -445,7 +438,7 @@ public class QueryUtilsUnitTests {
String fullQuery = applySorting(query, sort);
assertThat(fullQuery, endsWith("order by authorName asc"));
assertThat(fullQuery).endsWith("order by authorName asc");
}
@Test // DATAJPA-1061
@@ -456,7 +449,7 @@ public class QueryUtilsUnitTests {
String fullQuery = applySorting(query, sort);
assertThat(fullQuery, endsWith("order by title asc"));
assertThat(fullQuery).endsWith("order by title asc");
}
@Test // DATAJPA-1061
@@ -467,18 +460,17 @@ public class QueryUtilsUnitTests {
String fullQuery = applySorting(query, sort);
assertThat(fullQuery, endsWith("order by m.price asc"));
assertThat(fullQuery).endsWith("order by m.price asc");
}
@Test
public void createCountQuerySupportsLineBreakRightAfterDistinct() {
assertThat(createCountQueryFor("select\ndistinct\nuser.age,\n" + //
"user.name\n" + //
"from\nUser\nuser")).isEqualTo(createCountQueryFor("select\ndistinct user.age,\n" + //
"user.name\n" + //
"from\nUser\nuser"), //
is(createCountQueryFor("select\ndistinct user.age,\n" + //
"user.name\n" + //
"from\nUser\nuser")));
"from\nUser\nuser"));
}
@Test
@@ -492,6 +484,6 @@ public class QueryUtilsUnitTests {
}
private static void assertCountQuery(String originalQuery, String countQuery) {
assertThat(createCountQueryFor(originalQuery), is(countQuery));
assertThat(createCountQueryFor(originalQuery)).isEqualTo(countQuery);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.query;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.jpa.repository.query.StoredProcedureAttributes.*;
import org.junit.Test;
@@ -25,6 +24,7 @@ import org.junit.Test;
* Unit tests for {@link StoredProcedureAttributes}.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
public class StoredProcedureAttributesUnitTests {
@@ -32,6 +32,6 @@ public class StoredProcedureAttributesUnitTests {
public void usesSyntheticOutputParameterNameForAdhocProcedureWithoutOutputName() {
StoredProcedureAttributes attributes = new StoredProcedureAttributes("procedure", null, Long.class, false);
assertThat(attributes.getOutputParameterName(), is(SYNTHETIC_OUTPUT_PARAMETER_NAME));
assertThat(attributes.getOutputParameterName()).isEqualTo(SYNTHETIC_OUTPUT_PARAMETER_NAME);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.lang.reflect.Method;
@@ -40,12 +39,31 @@ import org.springframework.transaction.support.TransactionSynchronizationManager
*
* @author Oliver Gierke
* @author Mark Paluch
* @author Jens Schauder
*/
@RunWith(MockitoJUnitRunner.class)
public class CrudMethodMetadataPopulatingMethodInterceptorUnitTests {
@Mock MethodInvocation invocation;
private static Sample expectLockModeType(final CrudMethodMetadata metadata, final LockModeType type) {
ProxyFactory factory = new ProxyFactory(new Object());
factory.addInterface(Sample.class);
factory.addAdvice(ExposeRepositoryInvocationInterceptor.INSTANCE);
factory.addAdvice(CrudMethodMetadataPopulatingMethodInterceptor.INSTANCE);
factory.addAdvice(new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) {
assertThat(metadata.getLockModeType()).isEqualTo(type);
return null;
}
});
return (Sample) factory.getProxy();
}
@Test // DATAJPA-268
public void cleansUpBoundResources() throws Throwable {
@@ -54,7 +72,7 @@ public class CrudMethodMetadataPopulatingMethodInterceptorUnitTests {
CrudMethodMetadataPopulatingMethodInterceptor interceptor = CrudMethodMetadataPopulatingMethodInterceptor.INSTANCE;
interceptor.invoke(invocation);
assertThat(TransactionSynchronizationManager.getResource(method), is(nullValue()));
assertThat(TransactionSynchronizationManager.getResource(method)).isNull();
}
@Test // DATAJPA-839, DATAJPA-1368
@@ -75,24 +93,6 @@ public class CrudMethodMetadataPopulatingMethodInterceptorUnitTests {
return method;
}
private static Sample expectLockModeType(final CrudMethodMetadata metadata, final LockModeType type) {
ProxyFactory factory = new ProxyFactory(new Object());
factory.addInterface(Sample.class);
factory.addAdvice(ExposeRepositoryInvocationInterceptor.INSTANCE);
factory.addAdvice(CrudMethodMetadataPopulatingMethodInterceptor.INSTANCE);
factory.addAdvice(new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) {
assertThat(metadata.getLockModeType(), is(type));
return null;
}
});
return (Sample) factory.getProxy();
}
interface Sample {
@Lock(LockModeType.OPTIMISTIC)

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;
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;
@@ -62,10 +61,8 @@ import org.springframework.stereotype.Component;
*/
public class DefaultJpaContextIntegrationTests {
public @Rule ExpectedException exception = ExpectedException.none();
static EntityManagerFactory firstEmf, secondEmf;
public @Rule ExpectedException exception = ExpectedException.none();
EntityManager firstEm, secondEm;
JpaContext jpaContext;
@@ -76,6 +73,26 @@ public class DefaultJpaContextIntegrationTests {
secondEmf = createEntityManagerFactory("querydsl");
}
private static final LocalContainerEntityManagerFactoryBean createEntityManagerFactoryBean(
String persistenceUnitName) {
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setPersistenceProvider(HibernateTestUtils.getPersistenceProvider());
factoryBean.setDataSource(
new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).generateUniqueName(true).build());
factoryBean.setPersistenceUnitName(persistenceUnitName);
return factoryBean;
}
private static final EntityManagerFactory createEntityManagerFactory(String persistenceUnitName) {
LocalContainerEntityManagerFactoryBean factoryBean = createEntityManagerFactoryBean(persistenceUnitName);
factoryBean.afterPropertiesSet();
return factoryBean.getObject();
}
@Before
public void createEntityManagers() {
@@ -96,7 +113,7 @@ public class DefaultJpaContextIntegrationTests {
@Test // DATAJPA-669
public void returnsEntitymanagerForUniqueType() {
assertThat(jpaContext.getEntityManagerByManagedType(Category.class), is(firstEm));
assertThat(jpaContext.getEntityManagerByManagedType(Category.class)).isEqualTo(firstEm);
}
@Test // DATAJPA-669
@@ -114,7 +131,7 @@ public class DefaultJpaContextIntegrationTests {
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
ApplicationComponent component = context.getBean(ApplicationComponent.class);
assertThat(component.context, is(notNullValue()));
assertThat(component.context).isNotNull();
context.close();
}
@@ -129,31 +146,11 @@ public class DefaultJpaContextIntegrationTests {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("config/jpa-context-with-jndi.xml");
ApplicationComponent component = context.getBean(ApplicationComponent.class);
assertThat(component.context, is(notNullValue()));
assertThat(component.context).isNotNull();
context.close();
}
private static final LocalContainerEntityManagerFactoryBean createEntityManagerFactoryBean(
String persistenceUnitName) {
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setPersistenceProvider(HibernateTestUtils.getPersistenceProvider());
factoryBean.setDataSource(
new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).generateUniqueName(true).build());
factoryBean.setPersistenceUnitName(persistenceUnitName);
return factoryBean;
}
private static final EntityManagerFactory createEntityManagerFactory(String persistenceUnitName) {
LocalContainerEntityManagerFactoryBean factoryBean = createEntityManagerFactoryBean(persistenceUnitName);
factoryBean.afterPropertiesSet();
return factoryBean.getObject();
}
@EnableJpaRepositories
@ComponentScan(includeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, value = ApplicationComponent.class),
useDefaultFilters = false)

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -32,6 +31,7 @@ import org.springframework.data.jpa.repository.query.DefaultJpaEntityMetadata;
*
* @author Oliver Gierke
* @author Christoph Strobl
* @author Jens Schauder
*/
public class DefaultJpaEntityMetadataUnitTest {
@@ -45,21 +45,21 @@ public class DefaultJpaEntityMetadataUnitTest {
public void returnsConfiguredType() {
DefaultJpaEntityMetadata<Foo> metadata = new DefaultJpaEntityMetadata<Foo>(Foo.class);
assertThat(metadata.getJavaType(), is(equalTo(Foo.class)));
assertThat(metadata.getJavaType()).isEqualTo(Foo.class);
}
@Test
public void returnsSimpleClassNameAsEntityNameByDefault() {
DefaultJpaEntityMetadata<Foo> metadata = new DefaultJpaEntityMetadata<Foo>(Foo.class);
assertThat(metadata.getEntityName(), is(Foo.class.getSimpleName()));
assertThat(metadata.getEntityName()).isEqualTo(Foo.class.getSimpleName());
}
@Test
public void returnsCustomizedEntityNameIfConfigured() {
DefaultJpaEntityMetadata<Bar> metadata = new DefaultJpaEntityMetadata<Bar>(Bar.class);
assertThat(metadata.getEntityName(), is("Entity"));
assertThat(metadata.getEntityName()).isEqualTo("Entity");
}
@Test // DATAJPA-871
@@ -67,7 +67,15 @@ public class DefaultJpaEntityMetadataUnitTest {
DefaultJpaEntityMetadata<BarWithComposedAnnotation> metadata = new DefaultJpaEntityMetadata<BarWithComposedAnnotation>(
BarWithComposedAnnotation.class);
assertThat(metadata.getEntityName(), is("Entity"));
assertThat(metadata.getEntityName()).isEqualTo("Entity");
}
@Entity
@Retention(RetentionPolicy.RUNTIME)
static @interface CustomEntityAnnotationUsingAliasFor {
@AliasFor(annotation = Entity.class, attribute = "name")
String entityName();
}
static class Foo {}
@@ -77,12 +85,4 @@ public class DefaultJpaEntityMetadataUnitTest {
@CustomEntityAnnotationUsingAliasFor(entityName = "Entity")
static class BarWithComposedAnnotation {}
@Entity
@Retention(RetentionPolicy.RUNTIME)
static @interface CustomEntityAnnotationUsingAliasFor {
@AliasFor(annotation = Entity.class, attribute = "name")
String entityName();
}
}

View File

@@ -15,12 +15,10 @@
*/
package org.springframework.data.jpa.repository.support;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import javax.persistence.TransactionRequiredException;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@@ -37,6 +35,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* Integration tests for disabling default transactions using JavaConfig.
*
* @author Oliver Gierke
* @author Jens Schauder
* @soundtrack The Intersphere - Live in Mannheim
*/
@RunWith(SpringJUnit4ClassRunner.class)
@@ -52,7 +51,7 @@ public abstract class DefaultTransactionDisablingIntegrationTests {
repository.findById(1);
assertThat(txManager.getDefinition().isReadOnly(), is(false));
assertThat(txManager.getDefinition().isReadOnly()).isFalse();
}
@Test // DATAJPA-685
@@ -60,15 +59,14 @@ public abstract class DefaultTransactionDisablingIntegrationTests {
repository.findAll(PageRequest.of(0, 10));
assertThat(txManager.getDefinition(), is(nullValue()));
assertThat(txManager.getDefinition()).isNull();
}
@Test // DATAJPA-685
public void persistingAnEntityShouldThrowExceptionDueToMissingTransaction() {
exception.expect(InvalidDataAccessApiUsageException.class);
exception.expectCause(is(Matchers.<Throwable> instanceOf(TransactionRequiredException.class)));
repository.saveAndFlush(new User());
assertThatThrownBy(() -> repository.saveAndFlush(new User())) //
.isInstanceOf(InvalidDataAccessApiUsageException.class) //
.hasCauseExactlyInstanceOf(TransactionRequiredException.class);
}
}

View File

@@ -15,7 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.io.Serializable;
@@ -41,7 +41,7 @@ public class EclipseLinkJpaMetamodelEntityInformationIntegrationTests
public void reactivatedDetectsIdTypeForMappedSuperclass() {
JpaEntityInformation<?, ?> information = JpaEntityInformationSupport.getEntityInformation(AbstractPersistable.class,
em);
assertEquals(String.class, information.getIdType());
assertThat(information.getIdType()).isEqualTo(String.class);
}
/**
@@ -92,8 +92,6 @@ public class EclipseLinkJpaMetamodelEntityInformationIntegrationTests
super.proxiedIdClassElement();
}
@Override
protected String getMetadadataPersitenceUnitName() {
return "metadata_el";

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
@@ -45,11 +44,33 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* Integration tests for {@link EntityManagerBeanDefinitionRegistrarPostProcessor}.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class EntityManagerBeanDefinitionRegistrarPostProcessorIntegrationTests {
@Autowired EntityManagerInjectionTarget target;
@Test // DATAJPA-445
public void injectsEntityManagerIntoConstructors() {
assertThat(target).isNotNull();
assertThat(target.em).isNotNull();
}
/**
* Annotation to demarcate test components.
*
* @author Oliver Gierke
*/
@Component
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
static @interface TestComponent {
}
@Configuration
@ImportResource("classpath:infrastructure.xml")
@ComponentScan(includeFilters = @Filter(TestComponent.class), useDefaultFilters = false)
@@ -84,15 +105,6 @@ public class EntityManagerBeanDefinitionRegistrarPostProcessorIntegrationTests {
}
}
@Autowired EntityManagerInjectionTarget target;
@Test // DATAJPA-445
public void injectsEntityManagerIntoConstructors() {
assertThat(target, is(notNullValue()));
assertThat(target.em, is(notNullValue()));
}
@TestComponent
static class EntityManagerInjectionTarget {
@@ -103,16 +115,4 @@ public class EntityManagerBeanDefinitionRegistrarPostProcessorIntegrationTests {
this.em = em;
}
}
/**
* Annotation to demarcate test components.
*
* @author Oliver Gierke
*/
@Component
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
static @interface TestComponent {
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import javax.persistence.EntityManagerFactory;
@@ -33,6 +32,7 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
* Unit tests for {@link EntityManagerBeanDefinitionRegistrarPostProcessor}.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
public class EntityManagerBeanDefinitionRegistrarPostProcessorUnitTests {
@@ -47,7 +47,7 @@ public class EntityManagerBeanDefinitionRegistrarPostProcessorUnitTests {
BeanFactoryPostProcessor processor = new EntityManagerBeanDefinitionRegistrarPostProcessor();
processor.postProcessBeanFactory(childFactory);
assertThat(beanFactory.getBeanDefinitionCount(), is(2));
assertThat(beanFactory.getBeanDefinitionCount()).isEqualTo(2);
}
@Test // DATAJPA-1005, DATAJPA-1045
@@ -62,7 +62,7 @@ public class EntityManagerBeanDefinitionRegistrarPostProcessorUnitTests {
BeanFactoryPostProcessor processor = new EntityManagerBeanDefinitionRegistrarPostProcessor();
processor.postProcessBeanFactory(beanFactory);
assertThat(beanFactory.getBeanDefinitionCount(), is(2));
assertThat(beanFactory.getBeanDefinitionCount()).isEqualTo(2);
}
interface SpecialEntityManagerFactory extends EntityManagerFactory {}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import javax.persistence.EntityManagerFactory;
@@ -31,6 +30,7 @@ import org.springframework.core.io.ClassPathResource;
* Assures the injected repository instances are wired to the customly configured {@link EntityManagerFactory}.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
public class EntityManagerFactoryRefUnitTests {
@@ -43,11 +43,11 @@ public class EntityManagerFactoryRefUnitTests {
BeanDefinition bean = factory.getBeanDefinition("userRepository");
Object value = getPropertyValue(bean, "entityManager");
assertTrue(value instanceof BeanDefinition);
assertThat(value instanceof BeanDefinition).isTrue();
BeanDefinition emCreator = (BeanDefinition) value;
BeanReference reference = getConstructorBeanReference(emCreator, 0);
assertThat(reference.getBeanName(), is("secondEntityManagerFactory"));
assertThat(reference.getBeanName()).isEqualTo("secondEntityManagerFactory");
}
private Object getPropertyValue(BeanDefinition definition, String propertyName) {
@@ -58,7 +58,7 @@ public class EntityManagerFactoryRefUnitTests {
private BeanReference getConstructorBeanReference(BeanDefinition definition, int index) {
Object value = definition.getConstructorArgumentValues().getIndexedArgumentValues().get(index).getValue();
assertTrue(value instanceof BeanReference);
assertThat(value instanceof BeanReference).isTrue();
return (BeanReference) value;
}
}

View File

@@ -15,7 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.io.Serializable;
@@ -35,6 +35,7 @@ import org.mockito.junit.MockitoJUnitRunner;
* Unit tests for {@link AbstractJpaEntityInformation}.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
@RunWith(MockitoJUnitRunner.class)
public class JpaEntityInformationSupportUnitTests {
@@ -46,10 +47,10 @@ public class JpaEntityInformationSupportUnitTests {
public void usesSimpleClassNameIfNoEntityNameGiven() throws Exception {
JpaEntityInformation<User, Long> information = new DummyJpaEntityInformation<User, Long>(User.class);
assertEquals("User", information.getEntityName());
assertThat(information.getEntityName()).isEqualTo("User");
JpaEntityInformation<NamedUser, ?> second = new DummyJpaEntityInformation<NamedUser, Serializable>(NamedUser.class);
assertEquals("AnotherNamedUser", second.getEntityName());
assertThat(second.getEntityName()).isEqualTo("AnotherNamedUser");
}
@Test(expected = IllegalArgumentException.class) // DATAJPA-93
@@ -63,11 +64,6 @@ public class JpaEntityInformationSupportUnitTests {
}
@Entity(name = "AnotherNamedUser")
public class NamedUser {
}
static class DummyJpaEntityInformation<T, ID> extends JpaEntityInformationSupport<T, ID> {
public DummyJpaEntityInformation(Class<T> domainClass) {
@@ -98,4 +94,9 @@ public class JpaEntityInformationSupportUnitTests {
return null;
}
}
@Entity(name = "AnotherNamedUser")
public class NamedUser {
}
}

View File

@@ -16,8 +16,7 @@
package org.springframework.data.jpa.repository.support;
import static java.util.Arrays.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.io.Serializable;
@@ -41,6 +40,7 @@ import org.springframework.data.jpa.domain.sample.PersistableWithIdClassPK;
* Unit tests for {@link JpaMetamodelEntityInformation}.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
@RunWith(MockitoJUnitRunner.Silent.class)
public class JpaMetamodelEntityInformationUnitTests {
@@ -77,9 +77,9 @@ public class JpaMetamodelEntityInformationUnitTests {
PersistableWithIdClass.class, metamodel);
PersistableWithIdClass entity = new PersistableWithIdClass(null, null);
assertThat(information.getId(entity), is(nullValue()));
assertThat(information.getId(entity)).isNull();
entity = new PersistableWithIdClass(2L, null);
assertThat(information.getId(entity), is(notNullValue()));
assertThat(information.getId(entity)).isNotNull();
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import javax.persistence.metamodel.EntityType;
@@ -35,6 +34,7 @@ import org.springframework.data.repository.core.EntityInformation;
* Unit tests for {@link JpaPersistableEntityInformation}.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
@RunWith(MockitoJUnitRunner.Silent.class)
public class JpaPersistableEntityInformationUnitTests {
@@ -61,12 +61,12 @@ public class JpaPersistableEntityInformationUnitTests {
metamodel);
Foo foo = new Foo();
assertThat(entityInformation.isNew(foo), is(false));
assertThat(entityInformation.getId(foo), is(nullValue()));
assertThat(entityInformation.isNew(foo)).isFalse();
assertThat(entityInformation.getId(foo)).isNull();
foo.id = 1L;
assertThat(entityInformation.isNew(foo), is(true));
assertThat(entityInformation.getId(foo), is(1L));
assertThat(entityInformation.isNew(foo)).isTrue();
assertThat(entityInformation.getId(foo)).isEqualTo(1L);
}
@SuppressWarnings("serial")

View File

@@ -15,7 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@@ -51,6 +51,7 @@ import org.springframework.data.repository.core.support.RepositoryFactorySupport
*
* @author Oliver Gierke
* @author Mark Paluch
* @author Jens Schauder
*/
@RunWith(MockitoJUnitRunner.Silent.class)
public class JpaRepositoryFactoryBeanUnitTests {
@@ -91,7 +92,7 @@ public class JpaRepositoryFactoryBeanUnitTests {
factoryBean.setBeanFactory(beanFactory);
factoryBean.afterPropertiesSet();
assertNotNull(factoryBean.getObject());
assertThat(factoryBean.getObject()).isNotNull();
}
@Test(expected = IllegalArgumentException.class)
@@ -109,23 +110,6 @@ public class JpaRepositoryFactoryBeanUnitTests {
new JpaRepositoryFactoryBean<Repository<Object, Long>, Object, Long>(null);
}
private class DummyJpaRepositoryFactoryBean<T extends JpaRepository<S, ID>, S, ID extends Serializable>
extends JpaRepositoryFactoryBean<T, S, ID> {
public DummyJpaRepositoryFactoryBean(Class<? extends T> repositoryInterface) {
super(repositoryInterface);
}
/*
* (non-Javadoc)
* @see org.springframework.data.jpa.predicateExecutor.support.JpaRepositoryFactoryBean#doCreateRepositoryFactory()
*/
@Override
protected RepositoryFactorySupport doCreateRepositoryFactory() {
return factory;
}
}
private interface SimpleSampleRepository extends JpaRepository<User, Integer> {
}
@@ -173,4 +157,21 @@ public class JpaRepositoryFactoryBeanUnitTests {
return null;
}
}
private class DummyJpaRepositoryFactoryBean<T extends JpaRepository<S, ID>, S, ID extends Serializable>
extends JpaRepositoryFactoryBean<T, S, ID> {
public DummyJpaRepositoryFactoryBean(Class<? extends T> repositoryInterface) {
super(repositoryInterface);
}
/*
* (non-Javadoc)
* @see org.springframework.data.jpa.predicateExecutor.support.JpaRepositoryFactoryBean#doCreateRepositoryFactory()
*/
@Override
protected RepositoryFactorySupport doCreateRepositoryFactory() {
return factory;
}
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.io.IOException;
@@ -90,7 +89,7 @@ public class JpaRepositoryFactoryUnitTests {
@Test
public void setsUpBasicInstanceCorrectly() throws Exception {
assertNotNull(factory.getRepository(SimpleSampleRepository.class));
assertThat(factory.getRepository(SimpleSampleRepository.class)).isNotNull();
}
@Test
@@ -105,8 +104,8 @@ public class JpaRepositoryFactoryUnitTests {
/**
* Asserts that the factory recognized configured predicateExecutor classes that contain custom method but no custom
* implementation could be found. Furthremore the exception has to contain the name of the predicateExecutor interface as for
* a large predicateExecutor configuration it's hard to find out where this error occured.
* implementation could be found. Furthremore the exception has to contain the name of the predicateExecutor interface
* as for a large predicateExecutor configuration it's hard to find out where this error occured.
*
* @throws Exception
*/
@@ -116,7 +115,7 @@ public class JpaRepositoryFactoryUnitTests {
try {
factory.getRepository(SampleRepository.class);
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().contains(SampleRepository.class.getName()));
assertThat(e.getMessage().contains(SampleRepository.class.getName())).isTrue();
}
}
@@ -150,7 +149,7 @@ public class JpaRepositoryFactoryUnitTests {
factory.setRepositoryBaseClass(CustomJpaRepository.class);
SampleRepository repository = factory.getRepository(SampleRepository.class);
assertEquals(CustomJpaRepository.class, ((Advised) repository).getTargetClass());
assertThat(((Advised) repository).getTargetClass()).isEqualTo(CustomJpaRepository.class);
}
@Test // DATAJPA-819
@@ -161,7 +160,7 @@ public class JpaRepositoryFactoryUnitTests {
factory.setBeanClassLoader(classLoader);
Object processor = ReflectionTestUtils.getField(factory, "crudMethodMetadataPostProcessor");
assertThat(ReflectionTestUtils.getField(processor, "classLoader"), is((Object) classLoader));
assertThat(ReflectionTestUtils.getField(processor, "classLoader")).isEqualTo((Object) classLoader);
}
private interface SimpleSampleRepository extends JpaRepository<User, Integer> {
@@ -182,7 +181,22 @@ public class JpaRepositoryFactoryUnitTests {
void throwingCheckedException() throws IOException;
}
/**
private interface SampleRepository extends JpaRepository<User, Integer>, SampleCustomRepository {
}
private interface QueryDslSampleRepository extends SimpleSampleRepository, QuerydslPredicateExecutor<User> {
}
static class CustomJpaRepository<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> {
public CustomJpaRepository(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
}
}
/**
* Implementation of the custom predicateExecutor interface.
*
* @author Oliver Gierke
@@ -198,20 +212,5 @@ public class JpaRepositoryFactoryUnitTests {
throw new IOException("You lose!");
}
}
private interface SampleRepository extends JpaRepository<User, Integer>, SampleCustomRepository {
}
private interface QueryDslSampleRepository extends SimpleSampleRepository, QuerydslPredicateExecutor<User> {
}
static class CustomJpaRepository<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> {
public CustomJpaRepository(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
}
};
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.Arrays;
import java.util.Optional;
@@ -27,10 +26,10 @@ import javax.persistence.PersistenceContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.jpa.domain.sample.SampleEntity;
import org.springframework.data.jpa.domain.sample.SampleEntityPK;
import org.springframework.data.jpa.domain.sample.PersistableWithIdClass;
import org.springframework.data.jpa.domain.sample.PersistableWithIdClassPK;
import org.springframework.data.jpa.domain.sample.SampleEntity;
import org.springframework.data.jpa.domain.sample.SampleEntityPK;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.test.context.ContextConfiguration;
@@ -42,6 +41,7 @@ import org.springframework.transaction.annotation.Transactional;
*
* @author Oliver Gierke
* @author Thomas Darimont
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:infrastructure.xml" })
@@ -65,13 +65,13 @@ public class JpaRepositoryTests {
SampleEntity entity = new SampleEntity("foo", "bar");
repository.saveAndFlush(entity);
assertThat(repository.existsById(new SampleEntityPK("foo", "bar")), is(true));
assertThat(repository.count(), is(1L));
assertThat(repository.findById(new SampleEntityPK("foo", "bar")), is(Optional.of(entity)));
assertThat(repository.existsById(new SampleEntityPK("foo", "bar"))).isTrue();
assertThat(repository.count()).isEqualTo(1L);
assertThat(repository.findById(new SampleEntityPK("foo", "bar"))).isEqualTo(Optional.of(entity));
repository.deleteAll(Arrays.asList(entity));
repository.flush();
assertThat(repository.count(), is(0L));
assertThat(repository.count()).isEqualTo(0L);
}
@Test // DATAJPA-50
@@ -80,12 +80,12 @@ public class JpaRepositoryTests {
PersistableWithIdClass entity = new PersistableWithIdClass(1L, 1L);
idClassRepository.save(entity);
assertThat(entity.getFirst(), is(notNullValue()));
assertThat(entity.getSecond(), is(notNullValue()));
assertThat(entity.getFirst()).isNotNull();
assertThat(entity.getSecond()).isNotNull();
PersistableWithIdClassPK id = new PersistableWithIdClassPK(entity.getFirst(), entity.getSecond());
assertThat(idClassRepository.findById(id), is(Optional.of(entity)));
assertThat(idClassRepository.findById(id)).isEqualTo(Optional.of(entity));
}
@Test // DATAJPA-266
@@ -94,9 +94,9 @@ public class JpaRepositoryTests {
PersistableWithIdClass s1 = idClassRepository.save(new PersistableWithIdClass(1L, 1L));
PersistableWithIdClass s2 = idClassRepository.save(new PersistableWithIdClass(2L, 2L));
assertThat(idClassRepository.existsById(s1.getId()), is(true));
assertThat(idClassRepository.existsById(s2.getId()), is(true));
assertThat(idClassRepository.existsById(new PersistableWithIdClassPK(1L, 2L)), is(false));
assertThat(idClassRepository.existsById(s1.getId())).isTrue();
assertThat(idClassRepository.existsById(s2.getId())).isTrue();
assertThat(idClassRepository.existsById(new PersistableWithIdClassPK(1L, 2L))).isFalse();
}
@Test // DATAJPA-527
@@ -105,19 +105,20 @@ public class JpaRepositoryTests {
PersistableWithIdClass entity = new PersistableWithIdClass(1L, 1L);
idClassRepository.save(entity);
assertThat(entity.getFirst(), is(notNullValue()));
assertThat(entity.getSecond(), is(notNullValue()));
assertThat(entity.getFirst()).isNotNull();
assertThat(entity.getSecond()).isNotNull();
PersistableWithIdClassPK id = new PersistableWithIdClassPK(entity.getFirst(), entity.getSecond());
assertThat(idClassRepository.existsById(id), is(true));
assertThat(idClassRepository.existsById(id)).isTrue();
}
private static interface SampleEntityRepository extends JpaRepository<SampleEntity, SampleEntityPK> {
}
private static interface SampleWithIdClassRepository extends CrudRepository<PersistableWithIdClass, PersistableWithIdClassPK> {
private static interface SampleWithIdClassRepository
extends CrudRepository<PersistableWithIdClass, PersistableWithIdClassPK> {
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.jpa.domain.JpaSort.*;
import java.util.List;
@@ -50,6 +49,7 @@ import org.springframework.transaction.annotation.Transactional;
*
* @author Thomas Darimont
* @author Oliver Gierke
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SampleConfig.class)
@@ -81,9 +81,9 @@ public class MailMessageRepositoryIntegrationTests {
new JpaSort(Direction.ASC, path(MailMessage_.mailSender).dot(MailSender_.name))));
List<MailMessage> messages = results.getContent();
assertThat(messages, hasSize(2));
assertThat(messages.get(0).getMailSender(), is(nullValue()));
assertThat(messages.get(1).getMailSender(), is(sender1));
assertThat(messages).hasSize(2);
assertThat(messages.get(0).getMailSender()).isNull();
assertThat(messages.get(1).getMailSender()).isEqualTo(sender1);
}
@Test // DATAJPA-12
@@ -103,9 +103,9 @@ public class MailMessageRepositoryIntegrationTests {
List<MailMessage> messages = mailMessageRepository.findAll(message.content.eq("abc"),
message.mailSender.name.asc());
assertThat(messages, hasSize(2));
assertThat(messages.get(0).getMailSender(), is(nullValue()));
assertThat(messages.get(1).getMailSender(), is(sender1));
assertThat(messages).hasSize(2);
assertThat(messages.get(0).getMailSender()).isNull();
assertThat(messages.get(1).getMailSender()).isEqualTo(sender1);
}
@Test // DATAJPA-491
@@ -129,9 +129,9 @@ public class MailMessageRepositoryIntegrationTests {
List<MailMessage> messages = mailMessageRepository.findAll(message.content.eq("abc"),
message.mailSender.mailUser.name.asc());
assertThat(messages, hasSize(2));
assertThat(messages.get(0).getMailSender(), is(nullValue()));
assertThat(messages.get(1).getMailSender(), is(sender1));
assertThat(messages).hasSize(2);
assertThat(messages.get(0).getMailSender()).isNull();
assertThat(messages.get(1).getMailSender()).isEqualTo(sender1);
}
@Test // DATAJPA-491
@@ -157,8 +157,8 @@ public class MailMessageRepositoryIntegrationTests {
List<MailMessage> messages = page.getContent();
assertThat(messages, hasSize(2));
assertThat(messages.get(0).getMailSender(), is(nullValue()));
assertThat(messages.get(1).getMailSender(), is(sender1));
assertThat(messages).hasSize(2);
assertThat(messages.get(0).getMailSender()).isNull();
assertThat(messages.get(1).getMailSender()).isEqualTo(sender1);
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@@ -37,6 +36,7 @@ import com.querydsl.jpa.JPQLQuery;
* Integration tests for {@link Querydsl}.
*
* @author Thomas Darimont
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:infrastructure.xml" })
@@ -62,7 +62,9 @@ public class QuerydslIntegrationTests {
JPQLQuery<User> result = querydsl.applySorting(Sort.by("firstname"), userQuery);
assertThat(result, is(notNullValue()));
assertThat(result.toString(), is(not(anyOf(containsString("nulls first"), containsString("nulls last")))));
assertThat(result).isNotNull();
assertThat(result.toString()) //
.doesNotContain("nulls first") //
.doesNotContain("nulls last");
}
}

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.List;
@@ -37,6 +36,7 @@ import org.springframework.transaction.annotation.Transactional;
*
* @author Oliver Gierke
* @author Thomas Darimont
* @author Jens Schauder
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:infrastructure.xml" })
@@ -68,43 +68,43 @@ public class QuerydslRepositorySupportTests {
public void readsUsersCorrectly() throws Exception {
List<User> result = repository.findUsersByLastname("Matthews");
assertThat(result.size(), is(1));
assertThat(result.get(0), is(dave));
assertThat(result.size()).isEqualTo(1);
assertThat(result.get(0)).isEqualTo(dave);
result = repository.findUsersByLastname("Beauford");
assertThat(result.size(), is(1));
assertThat(result.get(0), is(carter));
assertThat(result.size()).isEqualTo(1);
assertThat(result.get(0)).isEqualTo(carter);
}
@Test
public void updatesUsersCorrectly() throws Exception {
long updates = repository.updateLastnamesTo("Foo");
assertThat(updates, is(2L));
assertThat(updates).isEqualTo(2L);
List<User> result = repository.findUsersByLastname("Matthews");
assertThat(result.size(), is(0));
assertThat(result.size()).isEqualTo(0);
result = repository.findUsersByLastname("Beauford");
assertThat(result.size(), is(0));
assertThat(result.size()).isEqualTo(0);
result = repository.findUsersByLastname("Foo");
assertThat(result.size(), is(2));
assertThat(result, hasItems(dave, carter));
assertThat(result.size()).isEqualTo(2);
assertThat(result).contains(dave, carter);
}
@Test
public void deletesAllWithLastnameCorrectly() throws Exception {
long updates = repository.deleteAllWithLastname("Matthews");
assertThat(updates, is(1L));
assertThat(updates).isEqualTo(1L);
List<User> result = repository.findUsersByLastname("Matthews");
assertThat(result.size(), is(0));
assertThat(result.size()).isEqualTo(0);
result = repository.findUsersByLastname("Beauford");
assertThat(result.size(), is(1));
assertThat(result.get(0), is(carter));
assertThat(result.size()).isEqualTo(1);
assertThat(result.get(0)).isEqualTo(carter);
}
@Test(expected = IllegalArgumentException.class)

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.repository.support;
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;
@@ -35,6 +34,7 @@ import org.springframework.transaction.TransactionStatus;
* Integration test for transactional behaviour of predicateExecutor operations.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
@ContextConfiguration({ "classpath:config/namespace-autoconfig-context.xml", "classpath:tx-manager.xml" })
public class TransactionalRepositoryTests extends AbstractJUnit4SpringContextTests {
@@ -58,28 +58,28 @@ public class TransactionalRepositoryTests extends AbstractJUnit4SpringContextTes
public void simpleManipulatingOperation() throws Exception {
repository.saveAndFlush(new User("foo", "bar", "foo@bar.de"));
assertThat(transactionManager.getTransactionRequests(), is(1));
assertThat(transactionManager.getTransactionRequests()).isEqualTo(1);
}
@Test
public void unannotatedFinder() throws Exception {
repository.findByEmailAddress("foo@bar.de");
assertThat(transactionManager.getTransactionRequests(), is(0));
assertThat(transactionManager.getTransactionRequests()).isEqualTo(0);
}
@Test
public void invokeTransactionalFinder() throws Exception {
repository.findByAnnotatedQuery("foo@bar.de");
assertThat(transactionManager.getTransactionRequests(), is(1));
assertThat(transactionManager.getTransactionRequests()).isEqualTo(1);
}
@Test
public void invokeRedeclaredMethod() throws Exception {
repository.findById(1);
assertFalse(transactionManager.getDefinition().isReadOnly());
assertThat(transactionManager.getDefinition().isReadOnly()).isFalse();
}
@Test // DATACMNS-649
@@ -88,7 +88,7 @@ public class TransactionalRepositoryTests extends AbstractJUnit4SpringContextTes
User user = repository.saveAndFlush(new User("foo", "bar", "foo@bar.de"));
repository.deleteById(user.getId());
assertFalse(transactionManager.getDefinition().isReadOnly());
assertThat(transactionManager.getDefinition().isReadOnly()).isFalse();
}
public static class DelegatingTransactionManager implements PlatformTransactionManager {

View File

@@ -15,8 +15,7 @@
*/
package org.springframework.data.jpa.support;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.net.MalformedURLException;
@@ -37,15 +36,14 @@ import org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo;
* Unit test for {@link MergingPersistenceUnitManager}.
*
* @author Oliver Gierke
* @author Jens Schauder
*/
@RunWith(MockitoJUnitRunner.class)
public class MergingPersistenceUnitManagerUnitTests {
@Mock
PersistenceUnitInfo oldInfo;
@Mock PersistenceUnitInfo oldInfo;
@Mock
MutablePersistenceUnitInfo newInfo;
@Mock MutablePersistenceUnitInfo newInfo;
@Test
public void addsUrlFromOldPUItoNewOne() throws MalformedURLException {
@@ -67,11 +65,11 @@ public class MergingPersistenceUnitManagerUnitTests {
manager.preparePersistenceUnitInfos();
PersistenceUnitInfo info = manager.obtainPersistenceUnitInfo("pu");
assertThat(info.getManagedClassNames().size(), is(2));
assertThat(info.getManagedClassNames(), hasItems(User.class.getName(), Role.class.getName()));
assertThat(info.getManagedClassNames().size()).isEqualTo(2);
assertThat(info.getManagedClassNames()).contains(User.class.getName(), Role.class.getName());
assertThat(info.getMappingFileNames().size(), is(2));
assertThat(info.getMappingFileNames(), hasItems("foo.xml", "bar.xml"));
assertThat(info.getMappingFileNames().size()).isEqualTo(2);
assertThat(info.getMappingFileNames()).contains("foo.xml", "bar.xml");
}
@Test
@@ -85,8 +83,8 @@ public class MergingPersistenceUnitManagerUnitTests {
MergingPersistenceUnitManager manager = new MergingPersistenceUnitManager();
manager.postProcessPersistenceUnitInfo(newInfo, oldInfo);
assertThat(newInfo.getJarFileUrls().size(), is(1));
assertThat(newInfo.getJarFileUrls(), hasItems(oldInfo.getPersistenceUnitRootUrl()));
assertThat(newInfo.getJarFileUrls().size()).isEqualTo(1);
assertThat(newInfo.getJarFileUrls()).contains(oldInfo.getPersistenceUnitRootUrl());
}
@Test
@@ -99,7 +97,7 @@ public class MergingPersistenceUnitManagerUnitTests {
MergingPersistenceUnitManager manager = new MergingPersistenceUnitManager();
manager.postProcessPersistenceUnitInfo(newInfo, oldInfo);
assertThat(newInfo.getJarFileUrls().isEmpty(), is(true));
assertThat(newInfo.getJarFileUrls().isEmpty()).isTrue();
}
@Test
@@ -114,7 +112,7 @@ public class MergingPersistenceUnitManagerUnitTests {
MergingPersistenceUnitManager manager = new MergingPersistenceUnitManager();
manager.postProcessPersistenceUnitInfo(newInfo, oldInfo);
assertThat(newInfo.getJarFileUrls().size(), is(1));
assertThat(newInfo.getJarFileUrls(), hasItems(oldInfo.getPersistenceUnitRootUrl()));
assertThat(newInfo.getJarFileUrls().size()).isEqualTo(1);
assertThat(newInfo.getJarFileUrls()).contains(oldInfo.getPersistenceUnitRootUrl());
}
}

View File

@@ -1,232 +0,0 @@
/*
* Copyright 2017-2019 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
*
* https://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.jpa.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.persistence.AttributeNode;
import javax.persistence.EntityGraph;
import javax.persistence.Subgraph;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
/**
* @author Christoph Strobl
* @author Mark Paluch
*/
public class IsAttributeNode<T> extends TypeSafeMatcher<AttributeNode<T>> {
private boolean terminatingNodeCheck = false;
private List<String> nodes;
private List<String> subgraphs;
private final List<String> errors = new ArrayList<>();
@Override
protected boolean matchesSafely(AttributeNode<T> item) {
if (item == null) {
errors.add("AttributeNode was null!");
return false;
}
if (terminatingNodeCheck) {
if (!CollectionUtils.isEmpty(item.getSubgraphs())) {
errors.add(String.format("'%s' was expected to be a terminating node but has subgraphs %s.",
item.getAttributeName(), extractExistingAttributeNames(item.getSubgraphs().values().iterator().next())));
return false;
}
return true;
}
if (CollectionUtils.isEmpty(item.getSubgraphs())) {
if (!CollectionUtils.isEmpty(nodes)) {
errors
.add(String.format("Leaf properties %s could not be found. The node does not have any subgraphs.", nodes));
}
if (!CollectionUtils.isEmpty(subgraphs)) {
errors.add(String.format("Subgraphs %s could not be found. The node does not have any subgraphs.", subgraphs));
}
return false;
}
Subgraph<?> graph = item.getSubgraphs().values().iterator().next();
if (!CollectionUtils.isEmpty(nodes)) {
for (String nodeName : nodes) {
AttributeNode<?> node = findNode(nodeName, graph.getAttributeNodes());
if (node == null) {
errors.add(String.format("AttributeNode '%s' could not be found in subgraph for '%s'. Know nodes are: %s.",
nodeName, item.getAttributeName(), extractExistingAttributeNames(graph)));
return false;
}
if (!CollectionUtils.isEmpty(node.getSubgraphs())) {
errors.add(String.format("AttributeNode %s of subgraph %s is not a leaf property but has % SubGraph(s).",
nodeName, item.getAttributeName(), node.getSubgraphs().size()));
return false;
}
}
}
if (!CollectionUtils.isEmpty(subgraphs)) {
for (String subgraphName : subgraphs) {
AttributeNode<?> node = findNode(subgraphName, graph.getAttributeNodes());
if (node == null) {
errors.add(String.format("Subgraph '%s' could not be found in SubGraph for '%s'. Know nodes are: %s.",
subgraphName, item.getAttributeName(), extractExistingAttributeNames(graph)));
return false;
}
if (CollectionUtils.isEmpty(node.getSubgraphs())) {
errors.add(String.format("'%s' of SubGraph '%s' is not a SubGraph.", subgraphName, item.getAttributeName()));
return false;
}
}
}
return true;
}
@Override
public void describeTo(Description description) {
for (String error : errors) {
description.appendText(error);
}
}
/**
* Lookup the {@link AttributeNode} with given {@literal nodeName} in the root of the given {@literal graph}.
*
* @param nodeName
* @param graph
* @return
*/
public static AttributeNode<?> findNode(String nodeName, @Nullable EntityGraph<?> graph) {
if (graph == null) {
return null;
}
return findNode(nodeName, graph.getAttributeNodes());
}
/**
* Lookup the {@link AttributeNode} with given {@literal nodeName} in the {@link List} of given {@literal nodes}.
*
* @param nodeName
* @param nodes
* @return
*/
@Nullable
public static AttributeNode<?> findNode(String nodeName, List<AttributeNode<?>> nodes) {
if (CollectionUtils.isEmpty(nodes)) {
return null;
}
for (AttributeNode<?> node : nodes) {
if (ObjectUtils.nullSafeEquals(node.getAttributeName(), nodeName)) {
return node;
}
}
return null;
}
/**
* Lookup the {@link AttributeNode} with given {@literal nodeName} in the first {@link Subgraph} of the given
* {@literal node}.
*
* @param attributeName
* @param node
* @return
*/
@Nullable
public static AttributeNode<?> findNode(String attributeName, AttributeNode<?> node) {
if (CollectionUtils.isEmpty(node.getSubgraphs())) {
return null;
}
Subgraph<?> subgraph = node.getSubgraphs().values().iterator().next();
return findNode(attributeName, subgraph.getAttributeNodes());
}
private List<String> extractExistingAttributeNames(Subgraph<?> graph) {
List<String> result = new ArrayList<>(graph.getAttributeNodes().size());
for (AttributeNode<?> node : graph.getAttributeNodes()) {
result.add(node.getAttributeName());
}
return result;
}
/**
* Asserts that the fetch graph terminates with {@link AttributeNode}s having the given {@literal nodeNames}.
*
* @param nodeNames
* @return
*/
public static <T> IsAttributeNode<T> terminatesGraphWith(String... nodeNames) {
IsAttributeNode<T> matcher = new IsAttributeNode<>();
matcher.nodes = Arrays.asList(nodeNames);
return matcher;
}
/**
* Asserts that the fetch graph continues with {@link AttributeNode}s having {@link AttributeNode#getSubgraphs()} with
* given {@literal subgraphNames}.
*
* @return
*/
public static <T> IsAttributeNode<T> hasSubgraphs(String... subgraphNames) {
IsAttributeNode<T> matcher = new IsAttributeNode<>();
matcher.subgraphs = Arrays.asList(subgraphNames);
return matcher;
}
/**
* Asserts that the fetch graph terminates with the given {@link AttributeNode} by checking
* {@link AttributeNode#getSubgraphs()} is empty.
*
* @return
*/
public static <T> IsAttributeNode<T> terminatesGraph() {
IsAttributeNode<T> matcher = new IsAttributeNode<>();
matcher.terminatingNodeCheck = true;
return matcher;
}
}