spring mvc模拟测试web应用程序上下文

时间:2013-07-12 21:46:48

标签: spring spring-mvc

@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>但是:< 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>

1 个答案:

答案 0 :(得分:1)

在视图解析器中,您是否将前缀值映射到“/ WEB-INF /”。如果是的话 你的

                .andExpect(forwardedUrl("test"));

应该是

              .andExpect(forwardedUrl("/WEB-INF/test.jsp"));
相关问题