Mockito 测试Controller
Controller类
LoginController.java
package org.jinglun.base.controller;
import javax.validation.Valid;
import org.jinglun.base.dto.LoginDto;
import org.jinglun.base.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping(value="/login")
public class LoginController {
private LoginService loginService;
@Autowired
LoginController(LoginService loginService) {
this.loginService = loginService;
}
@RequestMapping(value={"", "/"}, method=RequestMethod.POST)
public String login(@Valid LoginDto dto, BindingResult result) throws Exception {
if (result.hasErrors()) {
return "login";
}
if (loginService.login(dto)) {
return "home";
} else {
return "login";
}
}
}
测试类
LoginControllerTest.java
package org.jinglun.base.controller;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.any;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import org.jinglun.base.dto.LoginDto;
import org.jinglun.base.service.LoginService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:spring-web.xml","classpath:spring-dao.xml","classpath:spring-mybatis.xml","classpath:spring-service.xml"})
public class LoginControllerTest {
@Test
public void testLogin() throws Exception {
try {
LoginService service = mock(LoginService.class);
LoginController controller = new LoginController(service);
when(service.login(any(LoginDto.class))).thenReturn(true);
MockMvc mockmvc = standaloneSetup(controller).build();
mockmvc.perform(post("/login")
.param("username", "admin")
.param("password", "admin"))
.andExpect(view().name("home"));
}catch (Exception e) {
e.printStackTrace();
}
}
}