如何 运行 spring 隔离启动集成测试?
How to run spring boot integration tests isolated?
我想 运行 spring 启动集成测试完全相互隔离(这是 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 may be used as a class-level and method-level
annotation within the same class. In such scenarios, the
ApplicationContext will be marked as dirty after any such annotated
method as well as after the entire class. If the
DirtiesContext.ClassMode is set to AFTER_EACH_TEST_METHOD, the context
will be marked dirty after each test method in the class.
Annotation that can be applied to a test class to configure a test
database to use instead of any application defined or auto-configured
DataSource.
我想 运行 spring 启动集成测试完全相互隔离(这是 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 may be used as a class-level and method-level annotation within the same class. In such scenarios, the ApplicationContext will be marked as dirty after any such annotated method as well as after the entire class. If the DirtiesContext.ClassMode is set to AFTER_EACH_TEST_METHOD, the context will be marked dirty after each test method in the class.
Annotation that can be applied to a test class to configure a test database to use instead of any application defined or auto-configured DataSource.