I am trying to write unit test for a Rest api call which is having a POST method for adding a video file to web based application using Jersey2. Here is the signature of the method of my class(TemplateController.java
) for which I want to write unit test:
@POST
@Path("/video/add")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response addVideoData(
@Context HttpServletRequest request,
AttachmentDTO attachmentDTO) {
...
}
Here is my test method of the test class (TemplateControllerUnitTestCase.java
):
@Test
public void videoAdd_requestObjectIsNull_ResponseStatusIsOK() throws Exception {
// arrange
Builder builder = target("/target/video/add").request();
// action
final Response response = builder.post(Entity.entity(attachemntDTO, MediaType.APPLICATION_JSON));
// assertion
...
}
I'm able to pass the AttachmentDAO
object to the TemplateController
class from test class but unable to pass the request object which is becoming null in the method(addVideoData())
of the TemplateController.java class
.
I'm using RequestHelper
class which is a helper class for HttpServletRequest
, so I want to pass an object of this class to the method(addVideoData())
using Jersey2 test framework.
You can use the HK2 capabilities of Jersey 2, that helps with Dependency Injection. Doing it this way, you can create a
Factory
forHttpServletRequest
and return the mock from yourRequestHelper
. For exampleThen in your
JerseyTest
subclass, just register anAbstractBinder
with theResourceConfig
. For exampleAnother option
...is to not mock the
HttpServletRequest
at all, and use the actualHttpServletRequest
. To do that, we need to configure theDeploymentContext
as we override thegetDeploymentContext()
, and return aServletDeploymentContext
. You can see an example here and here. The first has also has an example of using aFactory
, while the second show an example of how to configure based on web.xml settings. If you chose the case for mocking theHttpServletRequest
, then you wouldn't need to override thegetTestContainerFactory
andconfigureDeployment
as seen in the examples. Simply using theApplication configure()
override is enough, as long as nothing else is dependent on servlet features.The examples in the link use
Extra
Both the example I linked to are trying to take advantage of the Sevlet features. So I'll give a complete example of using a request mock.
MockHttpServletRequest
is simple a dummy implementation ofHttpServletRequest
where I only override one methodgetMethod()
and always returnPOST
. You can see from the result, that even though it's aget
request, it still returnsPOST