在Spring Boot MVC单元测试中无法获得HAL格式

ais*_*siy 11 java spring spring-mvc spring-hateoas spring-boot

我正在尝试使用Spring Boot的Spring HATEOAS.我小心翼翼地写了一个单元测试:

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"));
Run Code Online (Sandbox Code Playgroud)

测试返回响应如下:

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

{
    "content": "Hello, World",
    "links": [
        {
            "rel": "self",
            "href": "http://localhost/greeting?name=World"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

但实际上,当我运行整个Spring Boot应用程序时,响应会像这样:

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"
}
Run Code Online (Sandbox Code Playgroud)

所以必须有一些方法来配置HATEOAS的响应,但我没有找到它.

希望熟悉此事的人可以帮助我.

整个存储库都在这里.

小智 5

问题是因为你正在使用 standaloneSetup()方法。这意味着您确实以编程方式构建了所有 Spring MVC,并且您的测试并不了解所有 Spring Boot '魔法'。因此这个测试有最少的 Spring MVC 基础设施,不知道如何使用 HATEOAS。

可能的解决方案是使用WebApplicationContext由 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"));
    }
}
Run Code Online (Sandbox Code Playgroud)