我正在使用 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"));
测试返回响应如下:
Content-Type: application/hal+json;charset=UTF-8
{
"content": "Hello, World",
"links": [
{
"rel": "self",
"href": "http://localhost/greeting?name=World"
}
]
}
但实际上,当我运行整个 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"
}
所以必须有一些方法来配置HATEOAS的响应,但我没有找到。
希望熟悉这方面的人可以帮助我。
整个存储库是here .
最佳答案
问题是因为您使用的是 standaloneSetup()
方法。这意味着您确实以编程方式构建了所有 Spring MVC,并且您的测试并不了解所有 Spring Boot 的“魔力”。因此这个测试有最小的 Spring MVC 基础设施,不知道如何使用 HATEOAS。
可能的解决方案是使用Spring Boot准备的WebApplicationContext
:
@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"));
}
}
关于java - 在 Spring Boot MVC 单元测试中无法获取 HAL 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44162857/