spring-boot-starter-test
springboottest 官网
springboottest手册
springboot手册
Spring Boot Reference Documentation
包含的一些包
“ spring-boot-starter-test”(在 中test scope)包含以下提供的库:
-
JUnit 5(包括与 JUnit 4 向后兼容的老式引擎):单元测试 Java 应用程序的事实标准。
-
Spring Test & Spring Boot Test:对 Spring Boot 应用程序的实用程序和集成测试支持。
-
AssertJ:一个流畅的断言库。
-
Hamcrest:匹配器对象库(也称为约束或谓词)。
-
Mockito:一个 Java 模拟框架。
-
JSONassert:JSON 的断言库。
-
JsonPath:JSON 的 XPath、
@SpringBootTest 测试启动注解
webEnvironment属性
-
MOCK(默认):加载网络ApplicationContext并提供模拟网络环境。使用此注释时不会启动嵌入式服务器。如果您的类路径上没有可用的 Web 环境,此模式会透明地回退到创建常规的非 WebApplicationContext. 它可以与您的 Web 应用程序结合使用@AutoConfigureMockMvc或@AutoConfigureWebTestClient用于基于模拟的测试。 -
RANDOM_PORT: 加载WebServerApplicationContext并提供真实的网络环境。嵌入式服务器启动并侦听随机端口。 -
DEFINED_PORT: 加载WebServerApplicationContext并提供真实的网络环境。嵌入式服务器启动并侦听定义的端口(来自您的application.properties)或默认端口8080。 -
NONE``ApplicationContext:通过使用加载SpringApplication但不提供任何网络环境(模拟或其他
@AutoConfigureMockMvc 自动注入MockMvc
默认情况下,@SpringBootTest不启动服务器。如果您有要针对此模拟环境测试的 Web 端点,您可以额外配置,MockMvc如以下示例所示:
@SpringBootTest
@AutoConfigureMockMvc
class MockMvcExampleTests {
@Test
void exampleTest(@Autowired MockMvc mvc) throws Exception {
mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Hello World"));
}
}
@ExtendWith(OutputCaptureExtension.class) 捕获输出拓展
@ExtendWith(OutputCaptureExtension.class)
class OutputCaptureTests {
@Test
void testName(CapturedOutput output) {
System.out.println("Hello World!");
assertThat(output).contains("World");
}
}
事务回滚
在类上添加,也可以在方法上添加 @Rollback 会回滚,@Rollback(false)不会回滚
@Rollback @Transactional
每个测试方法执行完之后就会回滚
2023-03-08 10:36:04.322 INFO 216844 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test: [DefaultTestContext@616fe72b testClass = ExampleOrderControllerTest2, testInstance = com.dzhou.controller.ExampleOrderControllerTest2@3f2d2f22,
更多推荐


所有评论(0)