Reputation: 10232
I am new to JerseyTest
. I have created a few unit tests for my controllers by following the numerous posts on the subject as well as the various questions on this site. I am using InMemoryTestContainerFactory
as my tests are very simple. However, there does not seem to be a way to set baseUri
during set up. What do I set my target to? My test classes extend the following class:
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);
}
Sample test class:
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));
}
}
None of the sample code available on this site seem to be configuring the baseUri
(see this for example). And yet, if I set it to some arbitrary value http://localhost:xxx
I get connection refused (obviously?). If I set it to just the path, I get the error base URL is not absolute
.
Upvotes: 0
Views: 2476
Reputation: 10232
Found the problem. I had overridden setUp() without calling super.setUp()
as a result of which TestContainer.start()
was not being called.
Upvotes: 0
Reputation: 209002
You can override URI getBaseUri()
in the JerseyTest
. The default is localhost:9998
But you don't really need to use this. JerseyTest
already has a Client
and WebTarget
(built from getBaseUri
) set up for you. All you need to call is target
to get it, e.g.
Response response = target().request().get();
// or
Response response = target("path").request().get();
Upvotes: 1