Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not get HAL format in Spring Boot MVC unit test

I am trying the Spring HATEOAS with Spring Boot. And I wrote a unit test with rest assured:

given().standaloneSetup(new GreetingApi())
        .accept("application/hal+json;charset=UTF-8")
        .when()
        .get("/greeting")
        .prettyPeek()
        .then().statusCode(200)
        .body("content", equalTo("Hello, World"))
        .body("_links.self.href", endsWith("/greeting?name=World"));

The test return response like this:

Content-Type: application/hal+json;charset=UTF-8

{
    "content": "Hello, World",
    "links": [
        {
            "rel": "self",
            "href": "http://localhost/greeting?name=World"
        }
    ]
}

But actually the response get like this when I run the whole Spring Boot Application:

HTTP/1.1 200 
Content-Type: application/hal+json;charset=UTF-8
Date: Wed, 24 May 2017 15:28:39 GMT
Transfer-Encoding: chunked

{
    "_links": {
        "self": {
            "href": "http://localhost:8080/greeting?name=World"
        }
    },
    "content": "Hello, World"
}

So there must be some method to configure the response for HATEOAS, but I didn't find it.

Hope someone who is familiar about this can help me.

The whole repository is here.

like image 303
aisensiy Avatar asked May 24 '17 15:05

aisensiy


1 Answers

The problem is because you are using standaloneSetup() method. Which means you do construct all the Spring MVC programmatically, and your test is not aware about all the Spring Boot 'magic'. Therefore this test have minimal Spring MVC infrastructure, which do not know how to work with HATEOAS.

The possible solution is to use WebApplicationContext prepared for by Spring Boot:

@RunWith(SpringRunner.class)
@SpringBootTest
public class GreetingApiTest {

    @Autowired
    private WebApplicationContext context;

    @Test
    public void should_get_a_content_with_self_link() throws Exception {
        given()
            .webAppContextSetup(context)
            .accept("application/hal+json;charset=UTF-8")
        .when()
            .get("/greeting")
            .prettyPeek()
        .then()
            .statusCode(200)
            .body("content", equalTo("Hello, World"))
            .body("_links.self.href", endsWith("/greeting?name=World"));
    }
}
like image 177
jumb0jet Avatar answered Sep 21 '22 05:09

jumb0jet