@Controller
public class MyController {
@RequestMapping(method = RequestMethod.GET, value = "/testParam")
public String update() {
return "test";
}
}
我的测试文件:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:/META-INF/config/applicationContext.xml"})
public class MyControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Test
public void testUpdate2() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
mockMvc.perform(get("/testParam")).andDo(print())
.andExpect(status().isOk())
.andExpect(forwardedUrl("test"));
}
@Test
public void testUpdate() throws Exception {
MockMvcBuilders.standaloneSetup(new MyController()).build()
.perform(get("/testParam")).andDo(print())
.andExpect(status().isOk())
.andExpect(forwardedUrl("test"));
}
}
问题 1):当我运行上述测试时,testUpdate2 失败并显示 AssertionError: Status expected <200> but was:<404>
2)如果是RequestMethod.POST,我该如何测试呢?
例如:
@RequestMapping(method = RequestMethod.POST, value = "/insert")
public String insertRequests() {
return "page";
}
测试:
@Test
public void insert() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
mockMvc.perform(post("/insert")).andDo(print())
.andExpect(status().isOk())
.andExpect(forwardedUrl("page"));
}
以上测试失败:AssertionError: Status expected <200> but was:<404>
编辑
我的 jsps 文件位于:“\src\main\webapp\WEB-INF\jsps\pages\test.jsp”我正在使用tiles.xml 文件配置。
xml文件:
<beans..>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsps/pages/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>