Java 模拟服务器-自定义对象作为REST响应

Java 模拟服务器-自定义对象作为REST响应,java,spring-boot,unit-testing,integration-testing,mockserver,Java,Spring Boot,Unit Testing,Integration Testing,Mockserver,我正在5.10.0版中使用Mock Server(Mock Server.com)在JUnit5测试中模拟REST-API。我正在用Java8开发一个spring引导应用程序。我的有效负载格式是“protobuf”,因此我的REST接口将返回一个响应属性。不幸的是,我在模拟服务器中找不到一个内置的解决方案,该解决方案将自定义对象作为主体由模拟服务器返回。我只找到了withBody(String)或withBody(byte[])等方法。除了这些方法之外,我还发现了一个方法withBody(Bod

我正在5.10.0版中使用Mock Server(Mock Server.com)在JUnit5测试中模拟REST-API。我正在用Java8开发一个spring引导应用程序。我的有效负载格式是“protobuf”,因此我的REST接口将返回一个
响应属性
。不幸的是,我在模拟服务器中找不到一个内置的解决方案,该解决方案将自定义对象作为主体由模拟服务器返回。我只找到了
withBody(String)
withBody(byte[])
等方法。除了这些方法之外,我还发现了一个方法
withBody(BodyWithContentType)
。我试图在我的单元测试类中创建抽象类
BodyWithContent
的以下实现/用法:

private final class MyProtoObjectPayloadBody extends BodyWithContentType<MyProtoObject> {

    public MyProtoObjectPayloadBody () {
        super(null, null);
    }

    @Override
    public MyProtoObject getValue() {
        // return logic of MyProtoObject
    }
}

// Called in @BeforeEach
private void prepareMock() {

    this.mockServer.when(HttpRequest.request().withMethod("GET").withPath("/my-path"))
                .respond(HttpResponse.response().withStatusCode(200).withBody(new MyProtoObjectPayloadBody ()).withDelay(TimeUnit.SECONDS, 5));
}

私有最终类MyProtoObjectPayloadBody扩展了BodyWithContentType{
公共MyProtoObjectPayloadBody(){
super(null,null);
}
@凌驾
公共MyProtoObject getValue(){
//MyProtoObject的返回逻辑
}
}
//在每个人之前打电话来
私有无效预处理块(){
this.mockServer.when(HttpRequest.request().withMethod(“GET”).withPath(“/my path”))
.respond(HttpResponse.response().withStatusCode(200).withBody(new MyProtoObjectPayloadBody()).withDelay(TimeUnit.SECONDS,5));
}
当我调试出现ResponseEntity的代码时,我从模拟服务器获得响应,但响应的“主体”总是空的。我的自定义
getValue()
也不会被调用。我确保应用程序逻辑中的REST调用结果来自使用不同返回代码的模拟服务器


有人能帮我解决这个问题吗?

不幸的是,我通过Slack得到了模拟服务器开发人员的回复,即不可能返回自定义对象。模拟服务器不清楚它们应该如何(反)序列化。因此,我将尝试通过byte[]

使用一种变通方法。不幸的是,我通过Slack得到了模拟服务器开发人员的回复,即不可能返回自定义对象。模拟服务器不清楚它们应该如何(反)序列化。因此,我将尝试通过byte[]

使用一种变通方法,您可以将对象的json响应返回为

mockServer.expect(ExpectedCount.once(),
                  MockRestRequestMatchers.requestTo(<URL>))
            .andRespond(MockRestResponseCreators.withSuccess(
                <json-response>, MediaType.APPLICATION_JSON))
mockServer.expect(ExpectedCount.once(),
MockRestRequestMatchers.requestTo())
.andRespond(模拟厕所应答器)成功(
,MediaType.APPLICATION(JSON))

您可以将对象的json响应返回为

mockServer.expect(ExpectedCount.once(),
                  MockRestRequestMatchers.requestTo(<URL>))
            .andRespond(MockRestResponseCreators.withSuccess(
                <json-response>, MediaType.APPLICATION_JSON))
mockServer.expect(ExpectedCount.once(),
MockRestRequestMatchers.requestTo())
.andRespond(模拟厕所应答器)成功(
,MediaType.APPLICATION(JSON))