springboot测试类
Controller测试类
/** * Created by zhiqi.shao on 2017/5/12. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes =MelonApplication.class) @WebAppConfiguration //启动一个真实web服务,然后调用Controller的Rest API,待单元测试完成之后再将web服务停掉 public class TestUserController { @Autowired protected WebApplicationContext wac; protected MockMvc mockMvc; //private TestRestTemplate restTemplate = new TestRestTemplate(); @Before public void setup() throws IOException { mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } @Test public void testf() throws Exception{ String updateResult = mockMvc.perform(MockMvcRequestBuilders.post("/admin/test").param("id", "4")) .andReturn() .getResponse() .getContentAsString(); System.out.println("----------查询----------" + updateResult); HttpServletResponse response= mockMvc.perform(MockMvcRequestBuilders.post("/admin/test").param("id", "4")) .andReturn() .getResponse(); System.out.println("***************************************************"+response); } }
Service测试类
/** * Created by zhiqi.shao on 2017/5/12. */ @Slf4j @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT) public class TestUserService { @Autowired private UserService userService; private Long id; @Before public void bf(){ log.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%defore");//设置要mock的Controller类,可以是多个 } @Test public void testAll() { this.saveUser(); this.getUser(); this.findAll(); this.delete(); } @Test public void saveUser(){ User user=new User(); user.setPassword("2345"); user.setEmail("zhiqi@123.com"); user.setPhone("1521088XXXXX"); user.setUsername("shaoshao"); userService.save(user); id=user.getUid(); log.info("id:"+id); } @Test public void getUser(){ User user=userService.getUser(3L); log.info(GSON.toJson(user)); } @Test public void findAll(){ List<User> users=userService.findAll(); log.info(GSON.toJson(users)); } @Test public void delete(){ userService.deleteUserById(3L); } }