我们如何在 junit 测试之间清除数据库

问题描述 投票:0回答:2

下面是一些支持@TestContainers功能的类

package com.changeorama.solidify;

import static org.junit.Assert.assertTrue;

import org.junit.jupiter.api.Test;
....

@Testcontainers
public class AbstractTest {
    
    @Container
    private static final PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>();


    static {
        postgres.start();
    }
    
    @Test
    void testPostgresIsRunning() {
        assertTrue(postgres.isRunning());
    }
    
    @DynamicPropertySource
    static void postgreSQLProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
        registry.add("spring.datasource.username", postgres::getUsername);
        registry.add("spring.datasource.password", postgres::getPassword);
    }
    
    
    
}   
package com.changeorama.solidify.repository;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.junit.jupiter.api.Test;
....

import lombok.extern.slf4j.Slf4j;

@Slf4j
@ActiveProfiles(profiles = "test")
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class CompartmentRepositoryTest extends AbstractTest{
    
    
    @Autowired
    CompartmentRepository compRepository;
    
    @Test
    void testSaveCompartment() {
      //Load test data
        CompartmentEntity comp = new CompartmentEntity();
        comp.setCompartmentId(12);
        comp.setCompartmentName(“Comp abc”);
        comp.setCompartmentSize(12);

        compRepository(comp);
        
    }
    
    
    @Test
    void testGetAllCompartments() {

        List<CompartmentEntity> comps = compRepository.findAll();
        assertThat(comps.isEmpty(), is(false));
    }
    
   
    
}

有没有办法使用 @Testcontainers 方法清理在同一测试套件中运行的测试之间的数据?

我们是否有能力在测试之间清除数据库?

如果@TestContainers 无法实现,我们是否可以手动清除数据?

java spring-boot testcontainers
2个回答
3
投票
  1. @Transactional

    注释你的测试类
    @Slf4j
    @ActiveProfiles(profiles = "test")
    @DataJpaTest
    @Transactional
    @AutoConfigureTestDatabase(replace=AutoConfigureTestDatabase.Replace.NONE)
    public class CompartmentRepositoryTest extends AbstractTest{
      //then your code
    }
    

当测试类用

@Transactional
注释时,其中的每个测试方法 该类层次结构在事务中运行,默认情况下它将在完成后自动回滚。

请注意

测试生命周期方法不支持
  • @Transactional

  • @Transactional

     注解但传播属性设置为 
    NOT_SUPPORTED
     
    (@Transactional = Propagation.NOT_SUPPORTED
    )
    的测试不会在事务中运行。

  1. 您可以在班级级别或测试方法上使用

    @Rollback

    
    

    @Test @Rollback(true) void testSaveCompartment() {}
    
    
    Rollback 表示测试方法完成后事务是否应该回滚。

0
投票
您可以使用 CompartmentRepository 中的

@BeforeEach

deleteAll
 方法(假设它实现了 JPARepository)在每次测试之前清除表,以便每个测试都以自己的数据开始。

@AfterEach public void setup() { compRepository.deleteAll() }
    
© www.soinside.com 2019 - 2024. All rights reserved.