* [BAEL-2557] Implement tests with Test Containers

* [BAEL-2557] Remove author info

* [BAEL-2557] Small refactor fixes

* [BAEL-2557] Remove duplicated property

* [BAEL-2557] Fix pmd rule violation
This commit is contained in:
FrancoCorleone 2019-02-12 06:09:37 +01:00 committed by Josh Cummings
parent c957ceaeba
commit 8a264439b7
14 changed files with 551 additions and 395 deletions

View File

@ -27,11 +27,27 @@
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<!-- Test containers only dependencies -->
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.10.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.5</version>
</dependency>
<!-- Test containers only dependencies -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>

View File

@ -1,14 +1,11 @@
package com.baeldung.config;
import java.util.Properties;
import javax.sql.DataSource;
import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl;
import com.baeldung.services.IBarService;
import com.baeldung.services.impl.BarSpringDataJpaService;
import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@ -21,10 +18,8 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.baeldung.dao.repositories.impl.ExtendedRepositoryImpl;
import com.baeldung.services.IBarService;
import com.baeldung.services.impl.BarSpringDataJpaService;
import com.google.common.base.Preconditions;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@ComponentScan({ "com.baeldung.dao", "com.baeldung.services" })
@ -32,6 +27,7 @@ import com.google.common.base.Preconditions;
@EnableJpaRepositories(basePackages = { "com.baeldung.dao" }, repositoryBaseClass = ExtendedRepositoryImpl.class)
@EnableJpaAuditing
@PropertySource("classpath:persistence.properties")
@Profile("!tc")
public class PersistenceConfiguration {
@Autowired

View File

@ -4,6 +4,7 @@ import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@ -19,6 +20,7 @@ import java.util.HashMap;
@Configuration
@PropertySource({"classpath:persistence-multiple-db.properties"})
@EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager")
@Profile("!tc")
public class PersistenceProductConfiguration {
@Autowired
private Environment env;

View File

@ -2,10 +2,7 @@ package com.baeldung.config;
import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
@ -20,6 +17,7 @@ import java.util.HashMap;
@Configuration
@PropertySource({"classpath:persistence-multiple-db.properties"})
@EnableJpaRepositories(basePackages = "com.baeldung.dao.repositories.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager")
@Profile("!tc")
public class PersistenceUserConfiguration {
@Autowired
private Environment env;

View File

@ -1,7 +1,6 @@
package com.baeldung.dao.repositories.user;
import com.baeldung.domain.user.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@ -21,13 +20,13 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
@Query("SELECT u FROM User u WHERE u.status = 1")
Collection<User> findAllActiveUsers();
@Query(value = "SELECT * FROM USERS.USERS u WHERE u.status = 1", nativeQuery = true)
@Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true)
Collection<User> findAllActiveUsersNative();
@Query("SELECT u FROM User u WHERE u.status = ?1")
User findUserByStatus(Integer status);
@Query(value = "SELECT * FROM USERS.Users u WHERE u.status = ?1", nativeQuery = true)
@Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true)
User findUserByStatusNative(Integer status);
@Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2")
@ -36,7 +35,7 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name);
@Query(value = "SELECT * FROM USERS.Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true)
@Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true)
User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name);
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
@ -48,7 +47,7 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
@Query("SELECT u FROM User u WHERE u.name like :name%")
User findUserByNameLikeNamedParam(@Param("name") String name);
@Query(value = "SELECT * FROM USERS.users u WHERE u.name LIKE ?1%", nativeQuery = true)
@Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true)
User findUserByNameLikeNative(String name);
@Query(value = "SELECT u FROM User u")
@ -57,7 +56,7 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
@Query(value = "SELECT u FROM User u ORDER BY id")
Page<User> findAllUsersWithPagination(Pageable pageable);
@Query(value = "SELECT * FROM USERS.Users ORDER BY id", countQuery = "SELECT count(*) FROM USERS.Users", nativeQuery = true)
@Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true)
Page<User> findAllUsersWithPaginationNative(Pageable pageable);
@Modifying
@ -65,6 +64,10 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name);
@Modifying
@Query(value = "UPDATE USERS.Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
@Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
int updateUserSetStatusForNameNative(Integer status, String name);
@Modifying
@Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true)
int updateUserSetStatusForNameNativePostgres(Integer status, String name);
}

View File

@ -1,13 +1,9 @@
package com.baeldung.domain.user;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.*;
@Entity
@Table(schema = "users")
@Table
public class Possession {
@Id

View File

@ -4,7 +4,7 @@ import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "users", schema = "users")
@Table(name = "users")
public class User {
@Id

View File

@ -0,0 +1,371 @@
package com.baeldung.dao.repositories;
import com.baeldung.dao.repositories.user.UserRepository;
import com.baeldung.domain.user.User;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.JpaSort;
import org.springframework.data.mapping.PropertyReferenceException;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
class UserRepositoryCommon {
final String USER_EMAIL = "email@example.com";
final String USER_EMAIL2 = "email2@example.com";
final String USER_EMAIL3 = "email3@example.com";
final String USER_EMAIL4 = "email4@example.com";
final Integer INACTIVE_STATUS = 0;
final Integer ACTIVE_STATUS = 1;
private final String USER_EMAIL5 = "email5@example.com";
private final String USER_EMAIL6 = "email6@example.com";
private final String USER_NAME_ADAM = "Adam";
private final String USER_NAME_PETER = "Peter";
@Autowired
protected UserRepository userRepository;
@Test
@Transactional
public void givenUsersWithSameNameInDB_WhenFindAllByName_ThenReturnStreamOfUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
userRepository.save(user3);
User user4 = new User();
user4.setName("SAMPLE");
user4.setEmail(USER_EMAIL4);
userRepository.save(user4);
try (Stream<User> foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) {
assertThat(foundUsersStream.count()).isEqualTo(3l);
}
}
@Test
public void givenUsersInDB_WhenFindAllWithQueryAnnotation_ThenReturnCollectionWithActiveUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
user1.setStatus(ACTIVE_STATUS);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
user3.setStatus(INACTIVE_STATUS);
userRepository.save(user3);
Collection<User> allActiveUsers = userRepository.findAllActiveUsers();
assertThat(allActiveUsers.size()).isEqualTo(2);
}
@Test
public void givenUsersInDB_WhenFindAllWithQueryAnnotationNative_ThenReturnCollectionWithActiveUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
user1.setStatus(ACTIVE_STATUS);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
user3.setStatus(INACTIVE_STATUS);
userRepository.save(user3);
Collection<User> allActiveUsers = userRepository.findAllActiveUsersNative();
assertThat(allActiveUsers.size()).isEqualTo(2);
}
@Test
public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotation_ThenReturnActiveUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotationNative_ThenReturnActiveUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationIndexedParams_ThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParams_ThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParams_ThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNames_ThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationIndexedParams_ThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLike("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNamedParams_ThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNative_ThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLikeNative("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindAllWithSortByName_ThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
List<User> usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
assertThat(usersSortByName.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test(expected = PropertyReferenceException.class)
public void givenUsersInDB_WhenFindAllSortWithFunction_ThenThrowException() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
List<User> usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindAllSortWithFunctionQueryAnnotationJPQL_ThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.findAllUsers(new Sort("name"));
List<User> usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationJPQL_ThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS));
Page<User> usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3));
assertThat(usersPage.getContent()
.get(0)
.getName()).isEqualTo("SAMPLE1");
}
@Test
public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationNative_ThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS));
Page<User> usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3));
assertThat(usersSortByNameLength.getContent()
.get(0)
.getName()).isEqualTo("SAMPLE1");
}
@Test
@Transactional
public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationJPQL_ThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS));
int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE");
assertThat(updatedUsersSize).isEqualTo(2);
}
@Test
public void givenUsersInDB_WhenFindByEmailsWithDynamicQuery_ThenReturnCollection() {
User user1 = new User();
user1.setEmail(USER_EMAIL);
userRepository.save(user1);
User user2 = new User();
user2.setEmail(USER_EMAIL2);
userRepository.save(user2);
User user3 = new User();
user3.setEmail(USER_EMAIL3);
userRepository.save(user3);
Set<String> emails = new HashSet<>();
emails.add(USER_EMAIL2);
emails.add(USER_EMAIL3);
Collection<User> usersWithEmails = userRepository.findUserByEmails(emails);
assertThat(usersWithEmails.size()).isEqualTo(2);
}
@After
public void cleanUp() {
userRepository.deleteAll();
}
}

View File

@ -1,28 +1,14 @@
package com.baeldung.dao.repositories;
import com.baeldung.config.PersistenceConfiguration;
import com.baeldung.dao.repositories.user.UserRepository;
import com.baeldung.domain.user.User;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.JpaSort;
import org.springframework.data.mapping.PropertyReferenceException;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
/**
@ -31,327 +17,7 @@ import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PersistenceConfiguration.class)
@DirtiesContext
public class UserRepositoryIntegrationTest {
private final String USER_NAME_ADAM = "Adam";
private final String USER_NAME_PETER = "Peter";
private final String USER_EMAIL = "email@example.com";
private final String USER_EMAIL2 = "email2@example.com";
private final String USER_EMAIL3 = "email3@example.com";
private final String USER_EMAIL4 = "email4@example.com";
private final String USER_EMAIL5 = "email5@example.com";
private final String USER_EMAIL6 = "email6@example.com";
private final Integer INACTIVE_STATUS = 0;
private final Integer ACTIVE_STATUS = 1;
@Autowired
private UserRepository userRepository;
@Test
@Transactional
public void givenUsersWithSameNameInDBWhenFindAllByNameThenReturnStreamOfUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
userRepository.save(user3);
User user4 = new User();
user4.setName("SAMPLE");
user4.setEmail(USER_EMAIL4);
userRepository.save(user4);
try (Stream<User> foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) {
assertThat(foundUsersStream.count()).isEqualTo(3l);
}
}
@Test
public void givenUsersInDBWhenFindAllWithQueryAnnotationThenReturnCollectionWithActiveUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
user1.setStatus(ACTIVE_STATUS);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
user3.setStatus(INACTIVE_STATUS);
userRepository.save(user3);
Collection<User> allActiveUsers = userRepository.findAllActiveUsers();
assertThat(allActiveUsers.size()).isEqualTo(2);
}
@Test
public void givenUsersInDBWhenFindAllWithQueryAnnotationNativeThenReturnCollectionWithActiveUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setEmail(USER_EMAIL);
user1.setStatus(ACTIVE_STATUS);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setEmail(USER_EMAIL3);
user3.setStatus(INACTIVE_STATUS);
userRepository.save(user3);
Collection<User> allActiveUsers = userRepository.findAllActiveUsersNative();
assertThat(allActiveUsers.size()).isEqualTo(2);
}
@Test
public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationThenReturnActiveUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationNativeThenReturnActiveUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationIndexedParamsThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParamsThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNamesThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setEmail(USER_EMAIL2);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationIndexedParamsThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLike("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNamedParamsThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNativeThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setEmail(USER_EMAIL);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLikeNative("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllWithSortByNameThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
List<User> usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
assertThat(usersSortByName.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test(expected = PropertyReferenceException.class)
public void givenUsersInDBWhenFindAllSortWithFunctionThenThrowException() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
List<User> usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllSortWithFunctionQueryAnnotationJPQLThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.findAllUsers(new Sort("name"));
List<User> usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0)
.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationJPQLThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS));
Page<User> usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3));
assertThat(usersPage.getContent()
.get(0)
.getName()).isEqualTo("SAMPLE1");
}
@Test
public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationNativeThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL4, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", USER_EMAIL5, INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL6, INACTIVE_STATUS));
Page<User> usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3));
assertThat(usersSortByNameLength.getContent()
.get(0)
.getName()).isEqualTo("SAMPLE1");
}
@Test
@Transactional
public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationJPQLThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS));
int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE");
assertThat(updatedUsersSize).isEqualTo(2);
}
public class UserRepositoryIntegrationTest extends UserRepositoryCommon {
@Test
@Transactional
@ -366,34 +32,4 @@ public class UserRepositoryIntegrationTest {
assertThat(updatedUsersSize).isEqualTo(2);
}
@Test
public void givenUsersInDBWhenFindByEmailsWithDynamicQueryThenReturnCollection() {
User user1 = new User();
user1.setEmail(USER_EMAIL);
userRepository.save(user1);
User user2 = new User();
user2.setEmail(USER_EMAIL2);
userRepository.save(user2);
User user3 = new User();
user3.setEmail(USER_EMAIL3);
userRepository.save(user3);
Set<String> emails = new HashSet<>();
emails.add(USER_EMAIL2);
emails.add(USER_EMAIL3);
Collection<User> usersWithEmails = userRepository.findUserByEmails(emails);
assertThat(usersWithEmails.size()).isEqualTo(2);
}
@After
public void cleanUp() {
userRepository.deleteAll();
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.dao.repositories;
import com.baeldung.domain.user.User;
import com.baeldung.util.BaeldungPostgresqlContainer;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import org.testcontainers.containers.PostgreSQLContainer;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created by adam.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({"tc", "tc-auto"})
public class UserRepositoryTCAutoIntegrationTest extends UserRepositoryCommon {
@ClassRule
public static PostgreSQLContainer postgreSQLContainer = BaeldungPostgresqlContainer.getInstance();
@Test
@Transactional
public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNativePostgres_ThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS));
userRepository.flush();
int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE");
assertThat(updatedUsersSize).isEqualTo(2);
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.dao.repositories;
import com.baeldung.domain.user.User;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import org.testcontainers.containers.PostgreSQLContainer;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("tc")
@ContextConfiguration(initializers = {UserRepositoryTCIntegrationTest.Initializer.class})
public class UserRepositoryTCIntegrationTest extends UserRepositoryCommon {
@ClassRule
public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:11.1")
.withDatabaseName("integration-tests-db")
.withUsername("sa")
.withPassword("sa");
@Test
@Transactional
public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNative_ThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", USER_EMAIL, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", USER_EMAIL2, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", USER_EMAIL3, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", USER_EMAIL4, ACTIVE_STATUS));
userRepository.flush();
int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE");
assertThat(updatedUsersSize).isEqualTo(2);
}
static class Initializer
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
TestPropertyValues.of(
"spring.datasource.url=" + postgreSQLContainer.getJdbcUrl(),
"spring.datasource.username=" + postgreSQLContainer.getUsername(),
"spring.datasource.password=" + postgreSQLContainer.getPassword()
).applyTo(configurableApplicationContext.getEnvironment());
}
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.util;
import org.testcontainers.containers.PostgreSQLContainer;
public class BaeldungPostgresqlContainer extends PostgreSQLContainer<BaeldungPostgresqlContainer> {
private static final String IMAGE_VERSION = "postgres:11.1";
private static BaeldungPostgresqlContainer container;
private BaeldungPostgresqlContainer() {
super(IMAGE_VERSION);
}
public static BaeldungPostgresqlContainer getInstance() {
if (container == null) {
container = new BaeldungPostgresqlContainer();
}
return container;
}
@Override
public void start() {
super.start();
System.setProperty("DB_URL", container.getJdbcUrl());
System.setProperty("DB_USERNAME", container.getUsername());
System.setProperty("DB_PASSWORD", container.getPassword());
}
@Override
public void stop() {
//do nothing, JVM handles shut down
}
}

View File

@ -0,0 +1,4 @@
# configuration for test containers testing
spring.datasource.url=${DB_URL}
spring.datasource.username=${DB_USERNAME}
spring.datasource.password=${DB_PASSWORD}

View File

@ -0,0 +1,4 @@
# configuration for Test Containers testing
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false