Unit testing SpringMVC测试MVC方法
我在控制器中有一个方法:Unit testing SpringMVC测试MVC方法,unit-testing,spring-mvc,mocking,Unit Testing,Spring Mvc,Mocking,我在控制器中有一个方法: @RequestMapping(value = "/", method = RequestMethod.GET) public final String mainGet(final HttpServletRequest request, final HttpServletResponse response, ModelMap model) throws ServletException { model.addAttribute(
@RequestMapping(value = "/", method = RequestMethod.GET)
public final String mainGet(final HttpServletRequest request,
final HttpServletResponse response, ModelMap model)
throws ServletException {
model.addAttribute("fontSize", fontSize);
courses = persistenceServices.getCourses();
model.addAttribute("coursesList", courses);
return "home";
}
我写了一个简单的测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:tests.xml" })
@WebAppConfiguration
public class TestHomeController {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Mock
private PersistenceServices persistenceServicesMock;
@InjectMocks
private HomeController homeController;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(homeController).build();
}
@Test
public void testMainGet() throws Exception {
mockMvc.perform( get("/")).andExpect(status().isOk()).andExpect(view().name("home"));
verify(persistenceServicesMock, times(1));
verifyNoMoreInteractions(persistenceServicesMock);
}
一切似乎都很好,但我不能调用任何MvcMock的方法。Eclipse在所有这些内容(执行、状态、视图等)下面加下划线,并向我显示以下信息:
The method perform(RequestBuilder) in the type MockMvc is not applicable for the arguments (MockHttpServletRequestBuilder)
我尝试将参数转换为RequestBuilder和ResultMatcher,但没有成功。尝试将
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
您是否静态导入get、状态、视图等?是的,我有类似的内容:导入静态org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;导入静态org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;删除wac声明。因为您使用的是独立设置,所以不需要它。另外,MockitoAnnotations.initMocks(this);应该在mockMVCbuilder之后调用。好的,我删除了wac。当我在mockMVCbuilder之后调用MockitoAnnotations.initMocks(this)时,我有NullPointerException。如果我在mockMVCbuilder之前有MockitoAnnotations.initMocks(此),我有一个错误:MockHttpServletRequestBuilder无法强制转换为RequestBuilder。NullPointer是因为您尚未初始化控制器。声明为:private HomeController HomeController=new HomeController();