在要测试的类上ctrl + shift + t 新建测试类
普通测试
@SpringBootTest
@RunWith(SpringRunner.class)
public class GirlServiceTest {
@Autowired
private GirlService girlService;
@Test
public void findById() throws Exception {
Girl girl = girlService.findById(1);
assertEquals(new Integer(20), girl.getAge());
}
}
controller层测试
模拟http请求
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class GirlControllerTest {
@Autowired
private MockMvc mvc;
/**
* andReturn().getResponse().getContentAsString() 会返回请求结果
**/
@Test
public void girlFindOne() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/girls/1"))
.andReturn().getResponse().getContentAsString() // 会返回请求结果
}
}