I am working on fixing the integration tests in one of the projects. Currently, all the integration test classes extend the JerseyTest class. Going through the JerseyTest class I realized that it starts and stops the container for every test method using Junit's Before and After annotations.
Why is this necessary? Isn't it enough if we bring up the container once, run the tests and shut it down at the end of it?
We also use Spring and it takes time for the context to get initialized.
Prior to Junit4 we worked around this limitation by handling it manually using boolean flags.
@Before
public void setup() {
if(!containerStarted) {
// start
containerStarted = true;
}
// else do nothing
}
You can use @BeforeClass and @AfterClass to override JerseyTest's @Before and @After lifecycle. Here is the code template:
Hope this is helpful.
We had a similar situations, using jersey plus spring as dependency injection framework (jersey-spring-bridge). Writing integration test with
JerseyTest
framework is tricky because it starts container before a test and stops the container after the test. This approach might have an advantage but, its very time consuming and tricky taking into account the fact that spring does scanning and autowiring of beans everytime.To achieve the above, I followed the following steps:
In the test class as instance variable, declare an instance of
HttpServer
as followNotice that I do not use
JerseyTest
because I want to handle the start/stop of test container myself. Now, you need to make use of@Before
and@AfterClass
to setup the server instance. In@Before
we will setup theserver
instance such that it load our custom filter/listener definitions in theweb.xml
(like programmatically loading the web.xml intoserver
instance)If you notice about I am using @Before but, the if condition will make it function as @BeforeClass. Don't exactly remember why I did not use
@BeforeClass
and my guess would be probably due to some of those configurations inside the if block. Anyway, give it a try if you are curious.web.xml
context init params such asapplicationContext
for example. WhereapplicationContext
contains spring-based configs.ctx
.server
with Grizzly instance by providing it URI and instance ofResourceConfig
WebappContext
which is nothing but, web.xml and now use it's deploy method to pass the server instance to it. This will run theWebappContext
configs and deploy it toserver
instance.And now you have a test running an instance of Grizzly with your web.xml plus spring-specific configs applied to the instance.
The
@AfterClass
could look as followAnd a sample test using REST-assured framework
The reason above works without specifying the base-path is because I set the REST-assured base path as follow
If you didn't want to use REST-assured then
Jersey-based imports