Vinoth Kumar C M
Vinoth Kumar C M

Reputation: 10598

How do we unit test this lambda expression?

We have a REST end point (JAX-RS) that is invoked from the browser. We are passing around OutputStream so that we could have the browser display the result of the call.

Here is the method.

@Path("/mypath/{userId}")
@POST
public Response createUser(@PathParam("userId") final int userId ) {
    StreamingOutput stream = (outputStream) -> {
        User user = userHelper.findUser(userId);
        userHelper.updateUser(user,outputStream);
    };

    return Response.ok(stream).build();
}

Using Junit and Mockito, how do we verify if userHelper.findUser and userHelper.updateUser has been called ?

Basically we just want to verify the interactions.

Upvotes: 5

Views: 3790

Answers (2)

UserF40
UserF40

Reputation: 3611

To "unit" test this you should create your test class and create a new instance of the class this method belongs to in the test class. The userHelper is not defined in the lambda so it is a class member? If so it can be mocked:

  • Create a mock userhelper object with Mockito
  • inject the mock to your test class.
  • Call the createUser method.
  • verify on the mock to assert the updateUser method is called once.
  • You can go a step further and verify what user and outputStream objects are passed using captors.

Upvotes: 2

Rudi Vankeirsbilck
Rudi Vankeirsbilck

Reputation: 164

The StreamingOutput is only called when somebody on the other end (typically the browser) start pulling from it. You test case will need to take over and (as suggested by the comments) start interaction with the Response.

Upvotes: 0

Related Questions