1.基于spring的单元测试
由于仅仅是单元测试是不够的,我们在做一个系统的时候往往需要不同层不同对象的交互,那么我们也就需要集成测试
@RunWith(SpringRunner.class)
@ContextConfiguration(classes="TestConfig.class")
@ActiveProfile("prod")
public class LlgWebSpringbootClassApplicationTests {
@Autowired
private TestBean testbean
@Test
public void contextLoads() {
System.out.println("111");
}
}
2.基于spring mvc 的单元测试
常用的代码在下方,具体其他细节请看官网
@SpringBootTest
public class LlgWebSpringbootClassApplicationTests {
private MockMvc mockMvc;
@Autowired
WebApplicationContext wac;
@Autowired
MockHttpSession session;
@Autowired
MockHttpServletRequest request;
@Before
public void setup(){
this.mockMvc= MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void testNormalController() throws Exception{
mockMvc.perform(get("/normal"))
.andExpect(status().isOk())
.andExpect(view().name("page"))
.andExpect(forwardedUrl("page.jsp"))
.andExpect(model().attribute("msg","success"));
}
@Test
public void testRestController()throws Exception{
mockMvc.perform(get("/testRest"))
.andExpect(status().isOk())
.andExpect(content().contentType("text/plain;charset=UTF-8"))
.andExpect(content().string("success"));
}
}
3.springboot测试
代码与之前的无太大区别,不再叙述,附上官方文档地址
https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/htmlsingle/#boot-features-testing
注意:在进行数据的模拟的时候,可以在类上加入一个@Transactional,则会自动回滚