After stream and lambda were introduced in Java after JDK 8, I am sure that most Java developers are actively using these new features in their projects. The questions around these components are how to unit test them? This post talks how to write the unit tests around these features.

Unit Testing Stream Pipelines

Since stream pipelines combine with lambdas to form a single unit, it is not obvious how to effectively unit test the pieces of the pipeline.

I have always followed these two guidelines to unit test those stream pipelines:

If the pipeline is simple enough, it can be wrapped in a method call, and it is enough to unit test the method call.

If the pipeline is more complex, pieces of the pipeline can be called from support methods, and the support methods can be unit tested.

For example, let's say we have a stream pipeline that maps all the letters of the word to uppercase and is wrapped in a java.util.function.Function<T,R> as below:

Unit Testing Lambdas

Believe me — it is very likely that you will encounter complex unit testing in real-world programming. The unit testing with complex lambdas, similar to unit testing of stream pipelines, can be simplified with following practices:

Replace a lambda that needs to be tested with a method reference and an auxiliary method.

Then, test the auxiliary method.

For example, I have a stream pipeline that involves a somewhat-complex lambda and a mapping class for the given string class name.

Conclusion

Writing unit tests is one of the core parts in software development. With new features introduced after JDK 8, it has become easier to write code concisely and declaratively. Only, the proper use of features, like streams and lambda, brings value and, of course, makes writing unit tests easier. If you have any additional guidelines for unit testing these features, don't stop yourself from sharing them in the comments. Until next time, happy coding!

The source code for the examples presented above is available on GitHub.