如何在JUnit测试之间对数据库进行清除操作。

huangapple go评论75阅读模式
英文:

How do we do a purge of the database in between junit tests

问题

以下是支持@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.save(comp);
    }
    
    @Test
    void testGetAllCompartments() {
        List<CompartmentEntity> comps = compRepository.findAll();
        assertThat(comps.isEmpty(), is(false));
    }
}

在同一个测试套件中运行的测试之间清理数据的方式是使用@Testcontainers方法吗?

在测试之间进行数据库的清除(purge)有可能吗?

如果无法在@TestContainers中实现,是否有任何方式可以手动清除数据?

英文:

Below are some of the classes that support @TestContainers functionality

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&lt;?&gt; postgres = new PostgreSQLContainer&lt;&gt;();


    static {
        postgres.start();
    }
    
    @Test
    void testPostgresIsRunning() {
        assertTrue(postgres.isRunning());
    }
    
    @DynamicPropertySource
    static void postgreSQLProperties(DynamicPropertyRegistry registry) {
        registry.add(&quot;spring.datasource.url&quot;, postgres::getJdbcUrl);
        registry.add(&quot;spring.datasource.username&quot;, postgres::getUsername);
        registry.add(&quot;spring.datasource.password&quot;, 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 = &quot;test&quot;)
@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&lt;CompartmentEntity&gt; comps = compRepository.findAll();
        assertThat(comps.isEmpty(), is(false));
    }
    
   
    
}

Is there a way clean up the data in between tests that run in the same test suite with the @Testcontainers approach?

Do we have an ability to do a purge of the database in between tests?

Is there anyway we can do a manual purge of data if not possible with @TestContainers?

答案1

得分: 2

  1. 使用 @Transactional 注解标记你的测试类

    @Slf4j
    @ActiveProfiles(profiles = "test")
    @DataJpaTest
    @Transactional
    @AutoConfigureTestDatabase(replace=AutoConfigureTestDatabase.Replace.NONE)
    public class CompartmentRepositoryTest extends AbstractTest{
      //然后是你的代码
    }
    

当一个测试类被标记为 @Transactional 时,该类层次结构内的每个测试方法都在一个事务中运行,默认情况下,这个事务在完成后会自动回滚

注意

  • 在测试生命周期方法上不支持使用 @Transactional
  • 被标记为 @Transactional 但传播属性被设置为 NOT_SUPPORTED (@Transactional = Propagation.NOT_SUPPORTED) 的测试不会在事务中运行。
  1. 你可以在类级别或测试方法上使用 @Rollback

    @Test
    @Rollback(true)
    void testSaveCompartment() {}
    
  • Rollback 表示在测试方法完成后是否应该回滚事务。
英文:
  1. Annotate your test class with @Transactional

    @Slf4j
    @ActiveProfiles(profiles = &quot;test&quot;)
    @DataJpaTest
    @Transactional
    @AutoConfigureTestDatabase(replace=AutoConfigureTestDatabase.Replace.NONE)
    public class CompartmentRepositoryTest extends AbstractTest{
      //then your code
    }
    

When a test class is annotated with @Transactional each test method within
that class hierarchy runs within a transaction that is by default it will rollback automatically after completion.

Note that

  • @Transactional is not supported on test lifecycle methods.

  • Tests that are annotated with @Transactional but have the propagation attribute set to NOT_SUPPORTED (@Transactional = Propagation.NOT_SUPPORTED) are not run within a transaction.

  1. You can use @Rollback on class level or test method

    @Test
    @Rollback(true)
    void testSaveCompartment() {}
    
  • Rollback indicates whether the transaction should be rolled back after the test method has completed.

答案2

得分: 0

你可以使用 @BeforeEach 注解和来自 CompartmentRepository 的 deleteAll 方法(假设它实现了 JPARepository),在每次测试之前清空表格,以便每个测试都以自己的数据开始。

@AfterEach
public void setup() {
    compRepository.deleteAll();
}
英文:

You can use @BeforeEach and deleteAll method from CompartmentRepository (assuming it implements JPARepository) to purge table before every test, so that each test start's with it's own data

@AfterEach
public void setup() {
    compRepository.deleteAll()
 }

huangapple
  • 本文由 发表于 2020年9月23日 02:56:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64016089.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定