Java MessageBodyProviderNotFoundException在使用GSON时在JerseyTest中抛出

Java MessageBodyProviderNotFoundException在使用GSON时在JerseyTest中抛出,java,gson,jersey-2.0,jersey-test-framework,Java,Gson,Jersey 2.0,Jersey Test Framework,我使用Jersey并决定使用GSON而不是Moxy来处理JSON(不喜欢Moxy需要setter的事实) 到目前为止,一切正常,除了我的JerseyTest子类中的一个非常恼人的问题:除非为每个调用明确注册,否则无法识别自定义GsonProvider。但是,如果我将应用程序部署到Tomcat,则可以识别它 我的ResourceConfig: @ApplicationPath("") public class MyResourceConfig extends ResourceConfig {

我使用Jersey并决定使用GSON而不是Moxy来处理JSON(不喜欢Moxy需要setter的事实)

到目前为止,一切正常,除了我的
JerseyTest
子类中的一个非常恼人的问题:除非为每个调用明确注册,否则无法识别自定义
GsonProvider
。但是,如果我将应用程序部署到Tomcat,则可以识别它

我的
ResourceConfig

@ApplicationPath("")
public class MyResourceConfig extends ResourceConfig {

    public MyResourceConfig() {
        register(GsonProvider.class);

        register(SomeResource.class);
    }
}
实施
GsonProvider
(尽管我认为这与我遇到的问题无关):

为了解决这个问题,我注册了
GsonProvider
,以获得请求。以下更改使测试通过:

public class SomeResourceTest extends JerseyTest {
    @Override
    public Application configure() {
        return new MyResourceConfig();
    }

    @Test
    public void someApi_200Returned() throws Exception {
        // Arrange
        // Act
        SomeResponse response =
                target("/somepath")
                        .register(GsonProvider.class)
                        .request()
                        .post(Entity.json(""), SomeResponse.class);
        // Assert
        assertThat(response.getStatus(), is(200));
    }
}
因此,在
MyResourceConfig
中注册
GsonProvider
有助于部署,但
JerseyTest
要求每个请求额外注册


虽然我可以接受,但这很烦人,很耗时,而且很难与其他团队成员沟通。这个问题有什么解决方案吗?

您还没有显示stacktrace,但是我非常确定,如果您仔细查看它,它将显示它实际上是一个客户端错误。您需要做的是向客户机注册gson提供程序,因为您正试图将响应JSON反序列化为POJO

@Override
public void configureClient(ClientConfig config) {
    config.register(GsonProvider.class)
}

configureClient
方法是
JerseyTest
中可以覆盖的方法。

是!我没有意识到客户端是一个独立的实体。ThanksI必须在任何电话中注册提供商,而且它确实起了作用。然而,我很确定有一个通用的方法来解决这个问题,而你的答案正是我所需要的。将此逻辑放入
MyJerseyTest
基类,生活又好了:)
public class SomeResourceTest extends JerseyTest {
    @Override
    public Application configure() {
        return new MyResourceConfig();
    }

    @Test
    public void someApi_200Returned() throws Exception {
        // Arrange
        // Act
        SomeResponse response =
                target("/somepath")
                        .register(GsonProvider.class)
                        .request()
                        .post(Entity.json(""), SomeResponse.class);
        // Assert
        assertThat(response.getStatus(), is(200));
    }
}
@Override
public void configureClient(ClientConfig config) {
    config.register(GsonProvider.class)
}