且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java 8 Lambdas的单元测试代码

更新时间:2023-12-04 08:23:52

您不能直接对lambda进行单元测试,因为它没有名称.除非您有对其的引用,否则无法调用它.

You can't unit test a lambda directly, since it doesn't have a name. There's no way to call it unless you have a reference to it.

通常的替代方法是将lambda重构为命名方法,并使用产品代码中的方法引用,然后从测试代码中按名称调用该方法.如您所述,这种情况无法通过这种方式重构,因为它捕获了foo,并且方法引用唯一可以捕获的是接收器.

The usual alternative is to refactor the lambda into a named method and use a method reference from product code and call the method by name from test code. As you note, this case can't be refactored this way because it captures foo, and the only thing that can be captured by a method reference is the receiver.

但是yshavit的答案谈到了一个重要的问题,即是否有必要对私有方法进行单元测试. Lambda当然可以视为私有方法.

But the answer from yshavit touches upon an important point about whether it's necessary to unit test private methods. A lambda can certainly be considered a private method.

这里还有一个更大的要点.单元测试的原则之一是,您不需要对太简单的东西进行单元测试.休息.这与lambda的理想情况非常吻合,该表达式非常简单,显然是正确的. (至少,这就是我认为的理想选择.)请考虑以下示例:

There's a larger point here too. One of the priciples of unit testing is that you don't need to unit test anything that's too simple to break. This aligns well with the ideal case for lambda, which is an expression that's so simple it's obviously correct. (At least, that's what I consider ideal.) Consider the example:

    baz -> baz.setFoo(foo)

是否有疑问,当此lambda表达式传递给Baz引用时,将调用其setFoo方法并将其作为参数传递给foo?也许它是如此简单以至于不需要进行单元测试.

Is there any doubt that this lambda expression, when handed a Baz reference, will call its setFoo method and pass it foo as an argument? Maybe it's so simple that it doesn't need to be unit tested.

另一方面,这仅是示例,也许您想要测试的实际lambda相当复杂.我看过使用大型嵌套多行lambda的代码.例如,请参见此答案及其问题和其他答案.这样的lambda确实很难调试和测试.如果lambda中的代码足够复杂以至于需要进行测试,那么也许应该将该代码重构出lambda,以便可以使用常规技术对其进行测试.

On the other hand, this is merely an example, and maybe the actual lambda you want to test is considerably more complicated. I've seen code that uses large, nested, multi-line lambdas. See this answer and its question and other answers, for example. Such lambdas are indeed difficult to debug and test. If the code in the lambda is complex enough that it warrants testing, maybe that code ought to be refactored out of the lambda, so that it can be tested using the usual techniques.