3

I am using Spring's "spring-test-mvc" library to test web controllers. I have a very simple controller that returns a JSON array. Then in my test I have:

@Test
public void shouldGetAllUsersAsJson() throws Exception {
    mockMvc.perform(get("/v1/users").accept(MediaType.APPLICATION_JSON))
            .andExpect(content().mimeType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("fName").exists());
}

The above test returns:

java.lang.AssertionError: No value for JSON path: fName

To quickly check what I actually get I ran the below test:

@Test
public void shouldPrintResults() throws Exception {
    mockMvc.perform(get("/v1/users").accept(MediaType.APPLICATION_JSON))
            .andDo(print());
}

And it returns the correct JSON array in the body of MockHttpServletResponse

I'm not sure why jsonPath is not able to see fName in the JSON array.

2 Answers 2

10

If you add the json path dependency to maven, or add the jar to your lib, then it will work. I think that Spring is not including the jsonPath dependency in the latest Spring 3.2.0 RC1 release. I'm guessing that this is the same for Spring-Test-MVC standalone project as well.

Here is the dependency for Maven:

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>0.8.1</version>
    <scope>test</scope>
</dependency>

You might also need the hamcrest library to use the jsonPath("$.test").value("test")

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-library</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>
Sign up to request clarification or add additional context in comments.

1 Comment

I have these dependencies in place. No luck. Same error message.
10

What does your json response body look like? You can see it by doing an .andDo(print())

You might want to try jsonPath("$.fName").

This is assuming that your json response is: {"fName":"first name"}

If your response is an array then you need jsonPath("$[0].fName") for a response like: [{"fName":"first name"},{"fName":"first name #2"}]

You can see more examples at: http://goessner.net/articles/JsonPath/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.