1
@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>
4

1 回答 1

1

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

                .andExpect(forwardedUrl("test"));

应该

              .andExpect(forwardedUrl("/WEB-INF/test.jsp"));
于 2013-07-13T00:27:00.563 回答