AKB
AKB

Reputation: 5938

spring mvc mock test web app context

@Controller
public class MyController {    

    @RequestMapping(method = RequestMethod.GET, value = "/testParam")
    public String update() {
        return "test";
    }
}

My Test file:

@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"));
        }
}

Question 1): When I run above tests, testUpdate2 fails saying AssertionError: Status expected <200> but was:<404>

2) If RequestMethod.POST, how can I test it?

eg:

@RequestMapping(method = RequestMethod.POST, value = "/insert")
    public String insertRequests() {
        return "page";
    }

Test:

@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"));
}

above Test fails: AssertionError: Status expected <200> but was:<404>

Edit

My jsps file is under location: "\src\main\webapp\WEB-INF\jsps\pages\test.jsp" i am using tiles.xml file configuration.

xml file:

 <beans..>
          <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsps/pages/" />
            <property name="suffix" value=".jsp" />
        </bean>
    </beans>

Upvotes: 1

Views: 1459

Answers (1)

sreeprasad
sreeprasad

Reputation: 3260

In your view resolver, did you map your prefix value to "/WEB-INF/". If so then your

                .andExpect(forwardedUrl("test"));

should be

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

Upvotes: 1

Related Questions