java - 在 Spring Boot MVC 单元测试中无法获取 HAL 格式

标签 java spring spring-mvc spring-boot spring-hateoas

我正在使用 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/

相关文章:

java - 同步方法的最佳方式

java - 无法打开 Hibernate Session 进行交易;嵌套异常是 org.hibernate.exception.JDBCConnectionException : Could not open connection

java - Spring MVC 启动期间如何找到基本 URL?

java - Android Studio 解析 JSON 对象不起作用

java - 如何在 checkout PTC Windchill 文档后获取其原始文件夹路径

java - Spring AOP从接口(interface)继承注解

java - spring bean 初始化取决于可变数量的其他 bean

java - 在共享目录中启动 Eclipse 产品

java - 数据库驱动程序需要支持分布式事务还是数据库本身需要支持?

Spring kafka 2.2类型映射类加载器不匹配