问题描述
我想运行完全相互隔离的spring boot集成测试(这是Kent Beck进行单元测试的想法)。因此,即使每个测试用例都有一个新的h2 db。但是我没有发现任何有用的东西。仅:使用@Before等等,但这不是一个好的解决方案。
这甚至可能吗?怎么样?
当然:我不在乎资源或时间效率。
Atm我使用junit 4.13和spring-boot-starter-test 2.2.6。
解决方法
您需要执行以下操作。
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)
@AutoConfigureTestDatabase(replace = Replace.ANY)
public class YourTest{
}
@DirtiesContext可用作类级别和方法级别 同一类中的注释。在这种情况下, 注释后,ApplicationContext将被标记为脏 方法以及整个类之后。如果 DirtiesContext.ClassMode设置为AFTER_EACH_TEST_METHOD,即上下文 将在该类中的每个测试方法之后将其标记为肮脏。
可以应用于测试类以配置测试的注释 要使用的数据库,而不是定义或自动配置的任何应用程序 数据源。