如何创建模拟数据库并在模拟数据库中添加数据,以便使用postgres db和java进行集成测试

如何创建模拟数据库并在模拟数据库中添加数据,以便使用postgres db和java进行集成测试,java,testing,integration,Java,Testing,Integration,我想执行集成测试,为其创建测试数据库并添加一些数据。 在进行集成测试时,我应该如何指向测试数据库 谢谢你的帮助……你可以用它来实现这一点。您可以通过观看这篇文章来了解这一点,以及如何在spring boot应用程序中配置它 为spring集成测试创建如下所示的配置 AbstractIT.java @Testcontainers @SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT, properties

我想执行集成测试,为其创建测试数据库并添加一些数据。 在进行集成测试时,我应该如何指向测试数据库

谢谢你的帮助……

你可以用它来实现这一点。您可以通过观看这篇文章来了解这一点,以及如何在spring boot应用程序中配置它

为spring集成测试创建如下所示的配置

AbstractIT.java

@Testcontainers
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {"spring.main.allow-bean-definition-overriding=true"})
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) // don't replace our DB with an in-memory one
@ContextConfiguration(initializers = AbstractIT.DockerPostgresDataSourceInitializer.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public abstract class AbstractIT {

    private static PostgreSQLContainer<?> postgresDBContainer = new PostgreSQLContainer<>("postgres:9.6")
            .withUrlParam("TC_DAEMON", "true")
            .withFileSystemBind("docker/db", "/docker-entrypoint-initdb.d", BindMode.READ_WRITE);

    static {
        postgresDBContainer.start();
    }

    public static class DockerPostgresDataSourceInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

        @Override
        public void initialize(ConfigurableApplicationContext applicationContext) {
            Assertions.assertNotNull(applicationContext);
            TestPropertySourceUtils.addInlinedPropertiesToEnvironment(
                    applicationContext,
                    "spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true",
                    "spring.datasource.driver-class-name="+postgresDBContainer.getDriverClassName(),
                    "spring.datasource.url=" + postgresDBContainer.getJdbcUrl(),
                    "spring.datasource.username=" + postgresDBContainer.getUsername(),
                    "spring.datasource.password=" + postgresDBContainer.getPassword()
            );
        }
    }
}
class UserControllerIT extends AbstractIT {

    @Autowired
    private TestRestTemplate template;

    @Autowired
    private UserRepository userRepository;

    @Test
    @Order(1)
    @DisplayName("Testing to get all the user details")
    void getAllUsersTest() {
        ResponseEntity<List<UserDTO>> response = this.template.exchange("/v1/users", GET, HttpEntity.EMPTY, new ParameterizedTypeReference<List<UserDTO>>() {
        });
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(response.getBody())
                .isNotEmpty()
                .hasSize(3)
                .extracting(UserDTO::getEmail).containsAnyOf("user1@some.com");
    }

    @Test
    @Order(2)
    @DisplayName("Testing for saving user details")
    void saveUsersTest() {
        ResponseEntity<Void> response = this.template.postForEntity("/v1/users", new HttpEntity<>(buildUserRequest()), Void.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
        long usersCount = userRepository.count();
        assertThat(usersCount).isEqualTo(4);
    }

    @Test
    @Order(3)
    @DisplayName("Testing to deleting user details by id")
    void deleteUsersTest() {

        this.template.delete("/v1/users/{id}", singleParam("id", "21"));

        boolean userExists = userRepository.existsById(21L);
        assertThat(userExists).isFalse();
    }

    @Test
    @Order(4)
    @DisplayName("Testing to finding user details by id")
    void findUserByIdTest() {
        ResponseEntity<UserDTO> response = this.template.getForEntity("/v1/users/{id}", UserDTO.class, singleParam("id", "22"));

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);

        assertThat(response.getBody())
                .extracting(UserDTO::getEmail, UserDTO::getFirstName, UserDTO::getLastName)
                .containsExactly("user2@some.com", "John", "Duke");
    }

    private UserDTO buildUserRequest() {
        return UserDTO.builder()
                .email("user4@some.com")
                .lastName("Maria")
                .firstName("Fernandes")
                .build();
    }

    private Map<String, String> singleParam(String key, String value) {
        Map<String, String> params = new HashMap<>();
        params.put(key, value);
        return params;
    }
}
@Testcontainers
@SpringBootTest(webEnvironment=SpringBootTest.webEnvironment.RANDOM_端口,属性={“spring.main.allow bean定义重写=true”})
@AutoConfigureTestDatabase(replace=AutoConfigureTestDatabase.replace.NONE)//不要用内存中的数据库替换我们的数据库
@ContextConfiguration(初始值设定项=AbstractIT.DockerPostgresDataSourceInitializer.class)
@TestMethodOrder(MethodOrder.OrderAnnotation.class)
公共抽象类AbstractIT{
私有静态PostgreSQLContainer postgresDBContainer=新的PostgreSQLContainer(“postgres:9.6”)
.withUrlParam(“TC_守护进程”、“true”)
.withFileSystemBind(“docker/db”,“/docker entrypoint initdb.d”,BindMode.READ\u WRITE);
静止的{
postgresDBContainer.start();
}
公共静态类DockerPostgresDataSourceInitializer实现ApplicationContextInitializer{
@凌驾
public void初始化(ConfigurableApplicationContext applicationContext){
assertNotNull(applicationContext);
TestPropertySourceUtils.AddInLinedProperties到环境(
应用上下文,
“spring.jpa.properties.hibernate.jdbc.lob.non_context_creation=true”,
“spring.datasource.driver类名=“+postgresDBContainer.getDriverClassName(),
“spring.datasource.url=“+postgresDBContainer.getJdbcUrl(),
“spring.datasource.username=“+postgresDBContainer.getUsername(),
“spring.datasource.password=“+postgresDBContainer.getPassword()
);
}
}
}
现在您可以编写集成测试,如下面的示例所示

UserControllerIT.java

@Testcontainers
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {"spring.main.allow-bean-definition-overriding=true"})
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) // don't replace our DB with an in-memory one
@ContextConfiguration(initializers = AbstractIT.DockerPostgresDataSourceInitializer.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public abstract class AbstractIT {

    private static PostgreSQLContainer<?> postgresDBContainer = new PostgreSQLContainer<>("postgres:9.6")
            .withUrlParam("TC_DAEMON", "true")
            .withFileSystemBind("docker/db", "/docker-entrypoint-initdb.d", BindMode.READ_WRITE);

    static {
        postgresDBContainer.start();
    }

    public static class DockerPostgresDataSourceInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

        @Override
        public void initialize(ConfigurableApplicationContext applicationContext) {
            Assertions.assertNotNull(applicationContext);
            TestPropertySourceUtils.addInlinedPropertiesToEnvironment(
                    applicationContext,
                    "spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true",
                    "spring.datasource.driver-class-name="+postgresDBContainer.getDriverClassName(),
                    "spring.datasource.url=" + postgresDBContainer.getJdbcUrl(),
                    "spring.datasource.username=" + postgresDBContainer.getUsername(),
                    "spring.datasource.password=" + postgresDBContainer.getPassword()
            );
        }
    }
}
class UserControllerIT extends AbstractIT {

    @Autowired
    private TestRestTemplate template;

    @Autowired
    private UserRepository userRepository;

    @Test
    @Order(1)
    @DisplayName("Testing to get all the user details")
    void getAllUsersTest() {
        ResponseEntity<List<UserDTO>> response = this.template.exchange("/v1/users", GET, HttpEntity.EMPTY, new ParameterizedTypeReference<List<UserDTO>>() {
        });
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(response.getBody())
                .isNotEmpty()
                .hasSize(3)
                .extracting(UserDTO::getEmail).containsAnyOf("user1@some.com");
    }

    @Test
    @Order(2)
    @DisplayName("Testing for saving user details")
    void saveUsersTest() {
        ResponseEntity<Void> response = this.template.postForEntity("/v1/users", new HttpEntity<>(buildUserRequest()), Void.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
        long usersCount = userRepository.count();
        assertThat(usersCount).isEqualTo(4);
    }

    @Test
    @Order(3)
    @DisplayName("Testing to deleting user details by id")
    void deleteUsersTest() {

        this.template.delete("/v1/users/{id}", singleParam("id", "21"));

        boolean userExists = userRepository.existsById(21L);
        assertThat(userExists).isFalse();
    }

    @Test
    @Order(4)
    @DisplayName("Testing to finding user details by id")
    void findUserByIdTest() {
        ResponseEntity<UserDTO> response = this.template.getForEntity("/v1/users/{id}", UserDTO.class, singleParam("id", "22"));

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);

        assertThat(response.getBody())
                .extracting(UserDTO::getEmail, UserDTO::getFirstName, UserDTO::getLastName)
                .containsExactly("user2@some.com", "John", "Duke");
    }

    private UserDTO buildUserRequest() {
        return UserDTO.builder()
                .email("user4@some.com")
                .lastName("Maria")
                .firstName("Fernandes")
                .build();
    }

    private Map<String, String> singleParam(String key, String value) {
        Map<String, String> params = new HashMap<>();
        params.put(key, value);
        return params;
    }
}
类UserControllerIT扩展了AbstractIT{ @自动连线 私有testrest模板; @自动连线 私有用户存储库用户存储库; @试验 @订单(1) @DisplayName(“测试以获取所有用户详细信息”) void getallusestest(){ ResponseEntity response=this.template.exchange(“/v1/users”,GET,HttpEntity.EMPTY,new ParameterizedTypeReference(){ }); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(response.getBody()) .isNotEmpty() .hasSize(3) .Extraction(UserDTO::getEmail).containsAnyOf(“user1@some.com"); } @试验 @订单(2) @DisplayName(“保存用户详细信息的测试”) void saveUsersTest(){ ResponseEntity response=this.template.postForEntity(“/v1/users”,新的HttpEntity(buildUserRequest()),Void.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED); long userscont=userRepository.count(); 资产(UserScont)。isEqualTo(4); } @试验 @订单(3) @DisplayName(“按id删除用户详细信息的测试”) void deleteUsersTest(){ delete(“/v1/users/{id}”,singleParam(“id”,“21”); 布尔userExists=userRepository.existsById(21L); assertThat(userExists).isFalse(); } @试验 @订单(4) @DisplayName(“通过id查找用户详细信息的测试”) void finduserbydtest(){ ResponseEntity response=this.template.getForEntity(“/v1/users/{id}”,UserDTO.class,singleParam(“id”,“22”); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(response.getBody()) .Extraction(UserDTO::getEmail、UserDTO::getFirstName、UserDTO::getLastName) .containsExactly(”user2@some.com“约翰”、“杜克”); } 私有UserDTO buildUserRequest(){ 返回UserDTO.builder() .电邮(“user4@some.com") .姓(“玛丽亚”) .名字(“费尔南德斯”) .build(); } 私有映射单参数(字符串键、字符串值){ Map params=新的HashMap(); 参数put(键、值); 返回参数; } } 您可以在此Github Repo下看到完整运行的应用程序-

您可以用来实现这一点。您可以通过观看这篇文章来了解这一点,以及如何在spring boot应用程序中配置它

为spring集成测试创建如下所示的配置

AbstractIT.java

@Testcontainers
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {"spring.main.allow-bean-definition-overriding=true"})
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) // don't replace our DB with an in-memory one
@ContextConfiguration(initializers = AbstractIT.DockerPostgresDataSourceInitializer.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public abstract class AbstractIT {

    private static PostgreSQLContainer<?> postgresDBContainer = new PostgreSQLContainer<>("postgres:9.6")
            .withUrlParam("TC_DAEMON", "true")
            .withFileSystemBind("docker/db", "/docker-entrypoint-initdb.d", BindMode.READ_WRITE);

    static {
        postgresDBContainer.start();
    }

    public static class DockerPostgresDataSourceInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

        @Override
        public void initialize(ConfigurableApplicationContext applicationContext) {
            Assertions.assertNotNull(applicationContext);
            TestPropertySourceUtils.addInlinedPropertiesToEnvironment(
                    applicationContext,
                    "spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true",
                    "spring.datasource.driver-class-name="+postgresDBContainer.getDriverClassName(),
                    "spring.datasource.url=" + postgresDBContainer.getJdbcUrl(),
                    "spring.datasource.username=" + postgresDBContainer.getUsername(),
                    "spring.datasource.password=" + postgresDBContainer.getPassword()
            );
        }
    }
}
class UserControllerIT extends AbstractIT {

    @Autowired
    private TestRestTemplate template;

    @Autowired
    private UserRepository userRepository;

    @Test
    @Order(1)
    @DisplayName("Testing to get all the user details")
    void getAllUsersTest() {
        ResponseEntity<List<UserDTO>> response = this.template.exchange("/v1/users", GET, HttpEntity.EMPTY, new ParameterizedTypeReference<List<UserDTO>>() {
        });
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(response.getBody())
                .isNotEmpty()
                .hasSize(3)
                .extracting(UserDTO::getEmail).containsAnyOf("user1@some.com");
    }

    @Test
    @Order(2)
    @DisplayName("Testing for saving user details")
    void saveUsersTest() {
        ResponseEntity<Void> response = this.template.postForEntity("/v1/users", new HttpEntity<>(buildUserRequest()), Void.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
        long usersCount = userRepository.count();
        assertThat(usersCount).isEqualTo(4);
    }

    @Test
    @Order(3)
    @DisplayName("Testing to deleting user details by id")
    void deleteUsersTest() {

        this.template.delete("/v1/users/{id}", singleParam("id", "21"));

        boolean userExists = userRepository.existsById(21L);
        assertThat(userExists).isFalse();
    }

    @Test
    @Order(4)
    @DisplayName("Testing to finding user details by id")
    void findUserByIdTest() {
        ResponseEntity<UserDTO> response = this.template.getForEntity("/v1/users/{id}", UserDTO.class, singleParam("id", "22"));

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);

        assertThat(response.getBody())
                .extracting(UserDTO::getEmail, UserDTO::getFirstName, UserDTO::getLastName)
                .containsExactly("user2@some.com", "John", "Duke");
    }

    private UserDTO buildUserRequest() {
        return UserDTO.builder()
                .email("user4@some.com")
                .lastName("Maria")
                .firstName("Fernandes")
                .build();
    }

    private Map<String, String> singleParam(String key, String value) {
        Map<String, String> params = new HashMap<>();
        params.put(key, value);
        return params;
    }
}
@Testcontainers
@SpringBootTest(webEnvironment=SpringBootTest.webEnvironment.RANDOM_端口,属性={“spring.main.allow bean定义重写=true”})
@AutoConfigureTestDatabase(replace=AutoConfigureTestDatabase.replace.NONE)//不要用内存中的数据库替换我们的数据库
@ContextConfiguration(初始值设定项=AbstractIT.DockerPostgresDataSourceInitializer.class)
@TestMethodOrder(MethodOrder.OrderAnnotation.class)
公共抽象类AbstractIT{
私有静态PostgreSQLContainer postgresDBContainer=新的PostgreSQLContainer(“postgres:9.6”)
.withUrlParam(“TC_守护进程”、“true”)
.withFileSystemBind(“docker/db”,“/docker entrypoint initdb.d”,BindMode.READ\u WRITE);
静止的{
postgresDBContainer.start();
}
公共静态类DockerPostgresDataSourceInitializer实现ApplicationContextInitializer{
@凌驾
public void初始化(ConfigurableApplicationContext applicationContext){
assertNotNull(applicationContext);
TestPropertySourceUtils.ad