通过Mockito的API来MockUserService.getUsername(long id)方法,@Controller的测试代码如下:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {
SpringMvcTestDemoApplication.class,
TestContext.class
})
@WebAppConfiguration
public class SpringMvcTestDemoApplicationTests {
@Autowired
UserService userService;
@Autowired
UserController controller;
MockMvc mockMvc;
@Before
public void init() {
this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void getUserById() throws Exception {
long id = 1L;
String ricky = "Ricky";
Mockito.when(userService.getUsername(id)).thenReturn(ricky);
this.mockMvc.perform(get("/users/" + id))
.andExpect(status().isOk())
.andExpect(content().string("username=" + ricky));
}
}