Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MockMvc returning 404 status

I am trying to write test cases for controller. I do not want to mock out my service as I would like to use these tests as complete functionality tests.

I am trying to test this controller:

@Controller
public class PlanController {

     @Autowired
     private PlanService planService;

     @RequestMapping(
        value = "/api/plans/{planId}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
     @ResponseBody
     @Nonnull
     @JsonView(Plan.SimpleView.class)
     public Plan getPlan(@RequestParam int orgId, @PathVariable int planId) {
         Plan plan = planService.getPlan(orgId, planId);
         return plan;
    }
}

and Here is test case I have written:

package com.videology.skunkworks.audiencediscovery.controller;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.eclipse.jetty.webapp.WebAppContext;  
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebAppContext.class})
@WebAppConfiguration
@EnableWebMvc
public class PlanControllerTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
    }

    @Test
    public void testGetPlan() throws Exception {
        mockMvc.perform(get("/api/plans/1/?orgId=1").accept(MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isOk());
    }
}

This test case is failing because status() being returned is 404 not 200. Not sure why it is returning 404 as errorMessage is null.

I have been through many similar questions but None of them were helpful for me.

like image 872
Gaurav Kumar Singh Avatar asked Jun 12 '16 14:06

Gaurav Kumar Singh


1 Answers

Error was in configuration. To Fix this, I had to provide my WebConfig file in contextConfiguration. Here is line I added:

@ContextConfiguration(classes = {WebConfig.class})
like image 156
Gaurav Kumar Singh Avatar answered Sep 23 '22 06:09

Gaurav Kumar Singh