2013-07-12 82 views
1
@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> 
+0

我不是弹簧, 熟悉并且但是我建议你在Chrome浏览器中使用F12。 你可以用它查看更多的信息,也可以自己解决问题! – 2013-07-12 22:03:48

+0

您可以添加类路径的代码片段:/META-INF/config/applicationContext.xml? – Hippoom

回答

1

在你的视图解析器,你映射你的前缀值设置为 “/ WEB-INF /”。如果是的话你

   .andExpect(forwardedUrl("test")); 

应该

   .andExpect(forwardedUrl("/WEB-INF/test.jsp")); 
+0

我给了.andExpect(forwardedUrl(“/ WEB-INF/jsps/pages/test.jsp”));,但仍然得到相同的错误。 – bekur

相关问题