@Controller
public class MyController {
@RequestMapping(method = RequestMethod.GET, value = "/testParam")
public String update() {
return "test";
}
}
我的測試文件:Spring MVC的模擬測試Web應用程序上下文
@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失敗說Asse田:狀態有望< 200>卻被:< 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異常:狀態預期< 200>但:< 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>
我不是彈簧, 熟悉並且但是我建議你在Chrome瀏覽器中使用F12。 你可以用它查看更多的信息,也可以自己解決問題! – 2013-07-12 22:03:48
您可以添加類路徑的代碼片段:/META-INF/config/applicationContext.xml? – Hippoom