0

我是新手JerseyTest。通过关注有关该主题的大量帖子以及该站点上的各种问题,我为我的控制器创建了一些单元测试。我正在使用InMemoryTestContainerFactory,因为我的测试非常简单。但是,在设置期间似乎没有设置方法baseUri。我的目标是什么?我的测试类扩展了以下类:

public abstract class ApiTest extends JerseyTest {

    @Override
    protected TestContainerFactory getTestContainerFactory() {
        return new InMemoryTestContainerFactory();
    }

    @Override
    protected ResourceConfig configure() {
        ResourceConfig rc = new ResourceConfig()
                .register(SpringLifecycleListener.class)
                .register(RequestContextFilter.class)
                .register(this)
                .property("contextConfig", new AnnotationConfigApplicationContext(ApplicationConfiguration.class));

        enable(TestProperties.LOG_TRAFFIC);
        enable(TestProperties.DUMP_ENTITY);
        forceSet(TestProperties.CONTAINER_PORT, "0");

        return configure(rc);
    }

    protected abstract ResourceConfig configure(ResourceConfig rc);
}

示例测试类:

public class ResourceTest extends ApiTest {

    private final Client webClient = ClientBuilder.newClient();

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Mock
    private ResourceService service;

    @Before
    public void setUp() throws Exception {
        initMocks(this);
    }

    @Override
    protected ResourceConfig configure(ResourceConfig rc) {
        rc.register(Resource.class);
        return rc;
    }

    @Test
    public void testGetResource() {

        Response response = webClient
                .target("http://localhost:8080")
                .path("/resource")
                .queryParam("id", "some_id_json")
                .request(MediaType.APPLICATION_JSON_TYPE)
                .get();

        assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST));
        assertThat(response.readEntity(Errors.class).getMessages().get(0), isA(String.class));
    }
}

此站点上可用的示例代码似乎都没有配置(例如,baseUri请参阅this )。然而,如果我将其设置为任意值http://localhost:xxx,我会拒绝连接(显然?)。如果我将它设置为路径,我会得到错误base URL is not absolute

4

2 回答 2

1

您可以URI getBaseUri()JerseyTest. 默认是localhost:9998

但是你真的不需要使用它。JerseyTest已经为您设置了Client and WebTarget(从 构建)。getBaseUri你只需要打电话就target可以得到它,例如

Response response = target().request().get();
// or
Response response = target("path").request().get();
于 2016-03-20T23:57:18.517 回答
0

发现了问题。我在没有调用的情况下覆盖了 setUp() super.setUp(),因此没有调用它TestContainer.start()

于 2016-03-21T03:13:01.973 回答