Spring Boot Test

使用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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容