简体   繁体   English

我们如何对这个lambda表达式进行单元测试?

[英]How do we unit test this lambda expression?

We have a REST end point (JAX-RS) that is invoked from the browser. 我们有一个从浏览器调用的REST端点(JAX-RS)。 We are passing around OutputStream so that we could have the browser display the result of the call. 我们传递OutputStream,以便我们可以让浏览器显示调用的结果。

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 ? 使用Junit和Mockito,我们如何验证是否已调用userHelper.findUseruserHelper.updateUser

Basically we just want to verify the interactions. 基本上我们只想验证交互。

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? userHelper没有在lambda中定义,所以它是一个类成员? If so it can be mocked: 如果是这样,它可以被嘲笑:

  • Create a mock userhelper object with Mockito 使用Mockito创建模拟 userhelper对象
  • inject the mock to your test class. mock 注入您的测试类。
  • Call the createUser method. 调用createUser方法。
  • verify on the mock to assert the updateUser method is called once. 在mock上验证断言updateUser方法被调用一次。
  • You can go a step further and verify what user and outputStream objects are passed using captors . 您可以更进一步,验证使用绑定器传递哪些user和outputStream对象。

The StreamingOutput is only called when somebody on the other end (typically the browser) start pulling from it. 仅当另一端(通常是浏览器)的某个人开始从中拉出时,才会调用StreamingOutput。 You test case will need to take over and (as suggested by the comments) start interaction with the Response. 您需要接管测试用例并(根据评论的建议)开始与Response进行交互。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM