【问题标题】:spring mvc mock test web app contextspring mvc 模拟测试 web 应用程序上下文
【发布时间】:2013-07-16 01:53:06
【问题描述】:
@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 but was:

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 but was:

编辑

我的 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>

【问题讨论】:

  • 我不熟悉spring,但我建议你在Chrome浏览器中使用F12。您可以使用它查看更多信息,也许可以自己解决问题!
  • 你能添加你的类路径的代码 sn-p:/META-INF/config/applicationContext.xml 吗?

标签: spring spring-mvc


【解决方案1】:

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

                .andExpect(forwardedUrl("test"));

应该是

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

【讨论】:

  • 我已经给出了.andExpect(forwardedUrl("/WEB-INF/jsps/pages/test.jsp"));,但仍然得到同样的错误。
猜你喜欢
  • 1970-01-01
  • 2013-04-03
  • 1970-01-01
  • 2018-07-20
  • 1970-01-01
  • 1970-01-01
  • 2011-04-23
  • 2013-08-18
  • 2012-01-20
相关资源
最近更新 更多