Atul
Atul

Reputation: 3377

Spring Junit test returns 404 error code

I am creating one Spring Junit class for testing one of my rest api. But when I called it, it return me 404 and the test case failed. The Junit test class is:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:config/spring-commonConfig.xml"})
public class SampleControllerTests {

public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(
        MediaType.APPLICATION_JSON.getType(),
        MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

@Test
public void testSampleWebService() throws Exception {
    mockMvc.perform(post("/sample/{userJson}", "{\"id\":\"102312121\",\"text\":\"Hi user\",\"key\":\"FIRST\"}"))
    .andExpect(status().isOk())
    .andExpect(jsonPath("$result", is("Hello ")))
    .andExpect(jsonPath("$answerKey", is("")));
}   
}

The RestController class is:

@RestController
public class SampleController {

private static final Logger logger = LoggerFactory.getLogger(SampleController.class);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").create();

@Autowired private SampleService sService;


@RequestMapping(value = "${URL.SAMPLE}", method = RequestMethod.POST)
@ResponseBody
public String sampleWebService(@RequestBody String userJson){
    String output="";
    try{
        output = sService.processMessage(userJson);
    }
    catch(Exception e){
        e.printStackTrace();
    }
    return output;
}
}   

I am loading the url string from property file. This way I am not hard coded the url in controller class but mapped it dynamically, so that is the reason I am loading the property files via class which I mentioned below.

"URL.SAMPLE=/sample/{userJson}"

The class which reads the property file where url is defined:

@Configuration
@PropertySources(value = {
    @PropertySource("classpath:/i18n/urlConfig.properties"),
    @PropertySource("classpath:/i18n/responseConfig.properties")
})
public class ExternalizedConfig {

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}
}

The error code 404 means, it is connect to server but not getting the source we requested. Can anybody tell me what exactly the issue is?

Thanks, Atul

Upvotes: 1

Views: 6974

Answers (2)

Atul
Atul

Reputation: 3377

Thanks for your response.

I have made the changes what you have suggested but the error was still persist.

So again I search with error and found the solution.

I made the changes in Spring xml file. Like:

Add namespace in xml file for mvc.

xmlns:mvc="http://www.springframework.org/schema/mvc"

http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc.xsd

   <context:component-scan base-package="XXX" />
<mvc:annotation-driven />

After this it is working.

Upvotes: 0

Sam Brannen
Sam Brannen

Reputation: 31288

You are currently attempting to have the JSON input parsed from the request body using @RequestBody; however, you are not submitting the content as the request body.

Instead, you are attempting to encode the request body within the URL, but it won't work like that.

To fix it, you'll need to do the following.

  1. Use /sample as the request path (not /sample/{userJson})
  2. Provide your test JSON input as the body of the request.

You can do the latter as follows.

@Test
public void testSampleWebService() throws Exception {
    String requestBody = "{\"id\":\"102312121\",\"text\":\"Hi user\",\"key\":\"FIRST\"}";

    mockMvc.perform(post("/sample").content(requestBody))
        .andExpect(status().isOk())
        .andExpect(jsonPath("$result", is("Hello ")))
        .andExpect(jsonPath("$answerKey", is("")));
}   

Upvotes: 2

Related Questions