使用Spring Boot 默认测试框架进行测试类的编写,需要加上
@RunWith(SpringRunner.class)@SpringBootTest
其中@SpringBootTest 是一个集合注解包含
@Target(value=TYPE)@Retention(value=RUNTIME)@Documented@Inherited@BootstrapWith(value=SpringBootTestContextBootstrapper.class)
主要作用是 传统spring-test 中 @ContextConfiguration 在spring boot 中的替代品,通过创建 ApplicationContext 来使得测试类被加入 SpringApplication。
不要忘记加上 @RunWith(SpringRunner.class) ,否则其他注解会被忽略
同时 spring-boot-starter-tester 还支持 mock 测试
private MockMvc mockMvc;
@Autowired
GreetingController greetingController ;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(greetingController).build();
}
@Test
public void testGreetingController() throws Exception {
RequestBuilder request = null;
request = get("/greeting");
MvcResult mvcResult = mockMvc.perform(request).andReturn();
int status = mvcResult.getResponse().getStatus();
String content = mvcResult.getResponse().getContentAsString();
Assert.assertEquals(200, status);
}
文章参考:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html