<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andrei Silviu Dragnea on Medium]]></title>
        <description><![CDATA[Stories by Andrei Silviu Dragnea on Medium]]></description>
        <link>https://medium.com/@andreisilviudragnea?source=rss-273c903587eb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*EY8v4RHrB4QO4TP_bVvGbw.jpeg</url>
            <title>Stories by Andrei Silviu Dragnea on Medium</title>
            <link>https://medium.com/@andreisilviudragnea?source=rss-273c903587eb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 14:27:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andreisilviudragnea/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Towards cleaner pure tests]]></title>
            <link>https://medium.com/@andreisilviudragnea/towards-cleaner-pure-tests-20f1356dee4c?source=rss-273c903587eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/20f1356dee4c</guid>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[testng]]></category>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Andrei Silviu Dragnea]]></dc:creator>
            <pubDate>Thu, 07 May 2020 12:52:31 GMT</pubDate>
            <atom:updated>2020-05-07T15:07:58.489Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_95IG2ErIguFA9sxkxTnqA.jpeg" /><figcaption>Credits: <a href="https://pixabay.com/photos/drops-of-water-water-liquid-fresh-578897/">https://pixabay.com/photos/drops-of-water-water-liquid-fresh-578897</a></figcaption></figure><p>The basic definition of <em>pure functions</em> is that they always have the same output for the same inputs and they do not alter the universe (they do not have side effects).</p><p>In this article, I define <em>pure tests</em> as the tests which mock interactions with external services. By mocking the interactions with the universe, we effectively purify the tested code, because we return the same fixed output for some matched input.</p><p>Being impure is not a problem, it’s just that pure tests <em>run the fastest</em> and they are <em>repeatable</em>, without any need for resource cleanup at the end of the test. This is why we should strive to write more pure tests.</p><h3>The technologies</h3><p>I want to present my idea of cleaner pure tests in the JVM world. The technologies involved in this article are:</p><ul><li>JUnit</li><li>TestNG</li><li>Mockito</li><li>AssertJ</li><li>The Spring Test Context framework</li><li>The Spring Boot Test framework</li><li>Project Reactor</li></ul><p>JUnit and TestNG are the most popular testing frameworks for Java. Each of them has its own peculiarities, which will be presented later.</p><p>Mockito is the most popular mocking framework for Java, with dedicated support in the Spring Boot Test framework.</p><p>AssertJ is a very useful assertion framework with many fluent-style assertion classes.</p><p>The Spring Test Context framework and the Spring Boot Test framework help when writing Spring integration tests. In this discussion, I will only consider Spring integration tests which mock interactions with external services.</p><p>Writing reactive code using the Spring framework implies using Project Reactor, which brings its own new challenges when it comes to cleaner tests.</p><h3>Pure tests hierarchy</h3><p>The hierarchy of pure tests includes:</p><ul><li>Tests for pure functions (usually static helper methods). These kinds of tests just provide inputs to the function and compare the output with the expected one. They are very simple to write, run and understand.</li><li>Traditional unit tests, which test a class at a time. The tested class can be, for example, a Spring Service. Each method of the service is tested by mocking the interactions of the method’s implementation with the service’s dependencies.</li><li>Spring integration tests, which can test the interaction of more application components at a time. For example, testing that an exception thrown by a Spring Service used by a Spring Controller is mapped to the expected HTTP response with the expected body. This test mocks the service’s response and then verifies the request mapping of the controller class and the exception handling of the ExceptionHandler bean.</li></ul><h3>JUnit vs TestNG comparison</h3><p>JUnit is a testing framework tailored for writing unit tests, as its name suggests.</p><p>TestNG, on the other hand, is a framework used for more complex test setups involving also end-to-end tests which call real systems (impure tests).</p><p>The relevant difference between JUnit and TestNG is the fact that JUnit creates a new instance of the test class for each test method, whereas TestNG does not do that.</p><p>Pure tests, just as unit tests, should be independent of each other and as simple as possible.</p><p>JUnit, by its design choice of having a new test instance for each test method, promotes pure tests independence, whereas when using TestNG, the programmer could be tempted to couple the pure tests between them.</p><p>I am going to present the testing approach I use for each of the three types of pure tests above, both in JUnit and TestNG.</p><h3>Testing pure functions</h3><p>Testing pure functions is not very different when using either JUnit or TestNG, because they do not have a test setup part. You simply pass some arguments to the tested method and compare the output with the expected one.</p><p>When using JUnit, each set of inputs and the corresponding expected output are provided to the test that calls the pure method with those inputs and compares the output with the expected one. Parameterised tests are the way to go when using JUnit for testing pure functions.</p><p>For example, testing a Fibonacci function looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b5821d4ff75e544201c5f9a029f531a/href">https://medium.com/media/6b5821d4ff75e544201c5f9a029f531a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bee40b486ce43a61301c55ab851c578f/href">https://medium.com/media/bee40b486ce43a61301c55ab851c578f/href</a></iframe><p>When using TestNG, each set of inputs and the corresponding expected output can be provided by using a DataProvider method. The tested method also needs, in this case, one test which takes the inputs and the expected output as arguments from the DataProvider method.</p><p>The test written using TestNG looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5842107c561e765925863f937b4b9dd9/href">https://medium.com/media/5842107c561e765925863f937b4b9dd9/href</a></iframe><p>I could say that, ironically, TestNG is the winner here, because less code needs to be written in this case.</p><p>Both JUnit and TestNG pure tests can easily be run in parallel, because there is no shared state between the tests.</p><h3>Traditional unit tests</h3><p>As an example, let’s test a UserService which uses a UserRepository for persisting the User entity it operates on. For simplicity, the User class has two fields: id and username. It also needs to correctly implement equality (equals() and hashCode() methods) for argument matching purposes and the toString() method for easier test debugging.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1f327566d4d8c020ef52bec1b6d9a7a/href">https://medium.com/media/c1f327566d4d8c020ef52bec1b6d9a7a/href</a></iframe><p>The UserService class has a dependency specified as a constructor argument and looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/121266c64be91fef4c455436709078ff/href">https://medium.com/media/121266c64be91fef4c455436709078ff/href</a></iframe><p>And the UserRepository looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcda81653c794c24b0afbb58e52aa9a3/href">https://medium.com/media/bcda81653c794c24b0afbb58e52aa9a3/href</a></iframe><p>When using JUnit, I create fields annotated with the Mockito’s Mock annotation in the test class for each dependency of the tested class. I also create a Before method where I call the constructor of the tested class with the mocked instances of its dependencies and assign it to a field of the test class. Before-annotated methods are executed before each test method.</p><p>Each test method tests only one method of the service at a time. The test method includes the test setup, which involves mocking the relevant interactions with the service’s dependencies. After the setup, the tested method is called and its output is checked.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3df8666a1a3b67fd37867dabd09d2c4/href">https://medium.com/media/d3df8666a1a3b67fd37867dabd09d2c4/href</a></iframe><p>Let’s see what happens with a unit test when it comes to how much mocking the test setup does:</p><ul><li>if the test setup does not mock all the required interactions, the test will fail</li><li>if the test setup mocks exactly the required interactions, the test will pass</li><li>if the test setup mocks more than the required interactions, the test will still pass</li></ul><p>The third case above is the source of dirty unit tests. Clean unit tests should mock exactly only what is needed for them to pass. Nothing more, nothing less.</p><p>Fortunately, the Mockito framework includes a Strict Stubbing mode, which enables two important features that help when writing clean unit tests:</p><ul><li>Early test failure with a helpful error message when the tested code cannot find a stubbing for a dependency of the tested class. In other words, while writing the test, it often happens that you mock an output for some inputs to a dependency of the tested class, but the actual tested code calls that method with different arguments. In Strict Stubbing mode, Mockito fails with an error saying what the actual values of the call were and what stubbings you have set up for the same called method, including the relevant lines of code. This way, you can fix the wrong value(s) of the actual call very fast, without using the debugger to see the actual vs expected value mismatch.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4e20edcc20a7adcdb7f56aa3fe3af61/href">https://medium.com/media/c4e20edcc20a7adcdb7f56aa3fe3af61/href</a></iframe><p>The test above fails with the following error, which helps you immediately identity the fact that the argument for the stubbed call should have been userToCreate instead of createdUser. The toString() implementation of the User class is the one displaying the actual vs expected value of the user argument.</p><pre>Strict stubbing argument mismatch. Please check:<br> - this invocation of &#39;create&#39; method:<br>    userRepository.create(<br>    User[id=&#39;null&#39;, <a href="/service/mailto:username=&#39;user@example.com">username=&#39;user@example.com</a>&#39;]<br>);<br>    -&gt; at UserService.create(UserService.java:10)<br> - has following stubbing(s) with different arguments:<br>    1. userRepository.create(<br>    User[id=&#39;userId&#39;, <a href="/service/mailto:username=&#39;user@example.com">username=&#39;user@example.com</a>&#39;]<br>);<br>      -&gt; at TestUserServiceJUnitPotentialStubbingProblem.testCreateUserPotentialStubbingProblem(TestUserServiceJUnitPotentialStubbingProblem.java:36)<br>Typically, stubbing argument mismatch indicates user mistake when writing tests.<br>Mockito fails early so that you can debug potential problem easily.</pre><ul><li>Automatic tracking of which stubbings are actually used by the tested method. If there is any stubbing unused in the test setup, Mockito will report it by failing the test at the end, also including the line of the unnecessary stubbing. This way, the test stays as short and simple as possible.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b92dd21edd98c351d21038269bd20d51/href">https://medium.com/media/b92dd21edd98c351d21038269bd20d51/href</a></iframe><p>The test above fails with the following error, which helps you clean up unused stubbings:</p><pre>Unnecessary stubbings detected.<br>Clean &amp; maintainable test code requires zero unnecessary code.<br>Following stubbings are unnecessary (click to navigate to relevant line of code):<br>  1. -&gt; at TestUserServiceJUnitUnnecessaryStubbing.testCreateUser(TestUserServiceJUnitUnnecessaryStubbing.java:35)<br>Please remove unnecessary stubbings or use &#39;lenient&#39; strictness. More info: javadoc for UnnecessaryStubbingException class.</pre><p>For JUnit, Mockito has dedicated support for Strict Stubbing mode, implemented by means of a JUnit Method Rule.</p><p>I did not mention setting up the mocks of a unit test in the Before method on purpose, because this is a sign of dirty tests. A stubbing should be present in the Before method only if it is really used by all the tests in the test class. From my experience, this is almost never the case, as each method of the tested class has a different functionality. However, when this actually happens, this is an important sign of a possible cross-cutting concern, such as logging of all the calls to the tested class, which maybe should be implemented as an aspect.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd064c8889fdf158e997dce9c70d6158/href">https://medium.com/media/fd064c8889fdf158e997dce9c70d6158/href</a></iframe><p>The test class above is an example of bad test setup in the Before method. Both tests would pass without Strict Stubbing support enabled, but Strict Stubbing makes them both fail with:</p><pre>Unnecessary stubbings detected.<br>Clean &amp; maintainable test code requires zero unnecessary code.<br>Following stubbings are unnecessary (click to navigate to relevant line of code):<br>  1. -&gt; at TestUserServiceJUnitUnnecessaryStubbingBeforeMethod.setUp(TestUserServiceJUnitUnnecessaryStubbingBeforeMethod.java:41)<br>Please remove unnecessary stubbings or use &#39;lenient&#39; strictness. More info: javadoc for UnnecessaryStubbingException class.</pre><pre>Unnecessary stubbings detected.<br>Clean &amp; maintainable test code requires zero unnecessary code.<br>Following stubbings are unnecessary (click to navigate to relevant line of code):<br>  1. -&gt; at TestUserServiceJUnitUnnecessaryStubbingBeforeMethod.setUp(TestUserServiceJUnitUnnecessaryStubbingBeforeMethod.java:37)<br>Please remove unnecessary stubbings or use &#39;lenient&#39; strictness. More info: javadoc for UnnecessaryStubbingException class.</pre><p>In order to clean the tests, the setup needs to be cut from the Before method and pasted at the beginning of each test method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6391da7c9318f2aee3581207f83c95af/href">https://medium.com/media/6391da7c9318f2aee3581207f83c95af/href</a></iframe><p>Running the refactored tests will make them fail again, but this time, each unused stubbing can be removed on a test-by-test basis.</p><pre>Unnecessary stubbings detected.<br>Clean &amp; maintainable test code requires zero unnecessary code.<br>Following stubbings are unnecessary (click to navigate to relevant line of code):<br>  1. -&gt; at TestUserServiceJUnitUnnecessaryStubbingBeforeMethodStep1.testCreateUser(TestUserServiceJUnitUnnecessaryStubbingBeforeMethodStep1.java:44)<br>Please remove unnecessary stubbings or use &#39;lenient&#39; strictness. More info: javadoc for UnnecessaryStubbingException class.</pre><pre>Unnecessary stubbings detected.<br>Clean &amp; maintainable test code requires zero unnecessary code.<br>Following stubbings are unnecessary (click to navigate to relevant line of code):<br>  1. -&gt; at TestUserServiceJUnitUnnecessaryStubbingBeforeMethodStep1.testGetUserById(TestUserServiceJUnitUnnecessaryStubbingBeforeMethodStep1.java:54)<br>Please remove unnecessary stubbings or use &#39;lenient&#39; strictness. More info: javadoc for UnnecessaryStubbingException class.</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0afe6cb7ce918d72a9a6abe89ede3706/href">https://medium.com/media/0afe6cb7ce918d72a9a6abe89ede3706/href</a></iframe><p>The tests end up cleaner and shorter, their setup is local to the test and minimal for the test to pass.</p><p>When it comes to stubbing setup, I also want to point out that eq argument matchers should be used as much as possible, because otherwise the unit test is pretty useless. The test needs to verify exactly how data flows through the tested method.</p><p>When using TestNG, the unit test setup happens in a BeforeMethod method. BeforeMethod-annotated methods are executed before each test method. TestNG also has other types of Before methods:</p><ul><li>BeforeClass methods, which execute only once for the whole test class instance.</li><li>BeforeTest methods, which execute before each test from an XML test suite file.</li></ul><p>However, the only Before method that should be used for clean unit tests is the BeforeMethod method. Using Mockito Strict Stubbing mode with TestNG drives the programmer to write clean unit tests. However, there is no direct Strict Stubbing support in Mockito for TestNG, but it can be easily provided by using a unit test base class, with a BeforeMethod method and AfterMethod method, which hook the MockitoSession object which implements Strict Stubbing into the TestNG test lifecycle.</p><p>Adding Mockito Strict Stubbing to an existing code base is rather straightforward (adding a TestRule to the test class for JUnit and extending a base class for TestNG). It transforms the existing unit tests by pushing down the test setup from higher levels (Before methods for JUnit or BeforeClass and BeforeMethod methods for TestNG) methods to the test method itself and removing the unnecessary test setup.</p><p>JUnit unit tests can be run in parallel by design, because each test method is independent of others, given the fact that there is a separate test instance for each test method. TestNG unit tests can be run in parallel, but only at test class level, because all test methods in a test class use the fields of the same test instance for mocked dependencies.</p><h3>Spring integration tests</h3><p>Before diving into how to write clean Spring integration tests, I want to point out a few details about how the Spring Test Context framework works.</p><p>The Spring application context used by the test class is, by default, re-used between the test methods of the same class, unless there is a DirtiesContext annotation on the test class, which signals that the test method dirties the context and it cannot be used by other test methods. Clean pure tests should never make use of the DirtiesContext annotation.</p><p>There is also a global ContextCache, which caches a Spring application context under a key determined by various components used to create and initialize the context (the set of Configuration classes, XML bean definition files, context initializers and so on). This means that, in some circumstances, a test context can be used across more than one test class, if the context key happens to be the same. However, if the programmer does not know about the application context caching mechanism, it almost never happens to use exactly the same application context for more than one test class.</p><p>The Spring Test Context framework is built around the TestExecutionListener interface, which has callback methods that react to the events of the Spring integration test lifecycle:</p><ul><li>beforeTestClass()</li><li>prepareTestInstance()</li><li>beforeTestMethod()</li><li>beforeTestExecution()</li><li>afterTextExecution()</li><li>afterTestMethod()</li><li>afterTestClass()</li></ul><p>The core functionality of the Spring Test Context framework is implemented by the following TestExecutionListeners:</p><ul><li>ServletTestExecutionListener</li><li>DirtiesContextBeforeModesTestExecutionListener</li><li>DependencyInjectionTestExecutionListener</li><li>DirtiesContextTestExecutionListener</li><li>TransactionalTestExecutionListener</li><li>SqlScriptsTestExecutionListener</li><li>EventPublishingTestExecutionListener</li></ul><p>The listeners are listed in their execution order. Their order is specified by the Spring ordering mechanism (Ordered interface or Order annotation) and is crucial to the correct functioning of the framework.</p><p>The relevant TestExecutionListener for our discussion is the DependencyInjectionTestExecutionListener, which injects dependencies from the application context into the Autowired-annotated fields of the test class. These are the mocked beans from the application context that a Spring integration test sets up for stubbing.</p><p>There is no support for Strict Stubbing in Mockito or Spring framework, but it can be implemented with a bit of work.</p><p>The main idea is to think about the lifecycle of a Mock object in a Spring integration test vs a unit test.</p><p>In the case of the unit test, a Mock object lives only as long as the unit test, both in the JUnit and TestNG case, if the tests are implemented as described in the section above.</p><p>In the case of a Spring integration test, a Mock object lives as long as the application context it is a part of, which can span even across test class boundaries. Since the same Mock object needs to be used by more test methods, even possibly from different test classes, it needs to be reset after each test method, in order not to interfere with the next test which uses the same application context. As as side note, the support for resetting mocks from Mockito has been implemented specifically for this use case.</p><p>In real-life code, the lifespan of a Mock object from a Spring integration test is usually tied to all the tests in a single test class, because the set of mocked objects in an application context changes on a test-by-test basis. In the case of the Spring Boot Test framework, each new mocked bean from the application context alters the application context key, so unless two test classes mock exactly the same set of classes, they will use different application contexts.</p><p>Since the Spring TestContext framework is decoupled from JUnit and TestNG, Strict Stubbing support can be implemented once and used both from JUnit-based and TestNG-based Spring integration tests.</p><p>After each test method, the application context needs to be scanned for Mock objects in order to reset them. In the Spring Boot Test framework, the ResetMocksTestExecutionListener is the one which resets the mocks in its afterTestMethod() method. The downside of this listener is that it only resets Mock objects introduced in the application context by means of the MockBean annotation. In the case of a code base which does not use MockBean, it will not work.</p><p>However, a new ResetAllMocksTestExecutionListener can be easily created, which essentially does the same thing as its Spring Boot Test counterpart, only that it resets all the mock objects it finds in the application context after each test. For example, it also resets the Mock beans introduced in the application context by directly using the Mockito.mock() call in a Bean method. The new listener should execute after the ResetMocksTestExecutionListener counterpart.</p><p>There needs to be another TestExecutionListener, which collects all the Mock objects from the application context in the beforeTestMethod(), in order to enable Strict Stubbing support on them. In its afterTestMethod(), the listener detaches Strict Stubbing support from the Mocks objects, in order to re-attach it before the next test, and it checks if there is any unused stubbing in the Spring integration test. Its name is StrictStubbingTestExecutionListener and it should verify unnecessary stubbing before ResetMocksTestExecutionListener or ResetAllMocksTestExecutionListener resets the mocks.</p><p>By using these two TestExecutionListeners, the Spring integration tests become cleaner without much effort.</p><p>For JUnit integration, the two listeners can be picked up by the Spring factories mechanism, if they are specified in a META-INF/spring-factories properties file from the classpath under the org.springframework.test.context.TestExecutionListener key. This mechanism is hooked into the SpringRunner used to annotate Spring integration tests run with JUnit.</p><p>For TestNG integration, a new base class called SpringIntegrationTestBase can be created by extending the AbstractTestNGSpringContextTests class and specifying the two additional TestExecutionListeners by using the TestExecutionListeners annotation.</p><p>Given the global nature of the ContextCache mechanism, which means that the Mock objects live longer than a test method, maybe even across test boundaries, Spring integration tests cannot be run in parallel. Even when setting up the application context for a Spring integration test takes a few hundred milliseconds, their inability of being run in parallel rapidly adds up to the total test execution time.</p><h3>Project Reactor tests</h3><p>Testing reactive code is a bit different, because reactive methods return a reactive type: a Mono or Flux Publisher. Until you subscribe and consume all the onNext() signals of the publisher, no computation actually happens.</p><p>This means that the test method needs to subscribe to the reactive publisher and make its assertions on the signals emitted by it. This can be done by either using StepVerifier from the reactor-test framework or just calling block() on the returned Mono (or if a Flux, .collectList().block()) and checking the result (or results from the list).</p><p>Testing pure functions which return reactive types is not any more different than what already stated above.</p><p>However, unit testing a class whose methods return reactive types needs additional framework support in order to keep the tests clean. This is because it is not enough for Mockito to check that all the stubbed method calls are actually used during the test. It also needs to check that the reactive publishers returned by those method calls are actually subscribed. Otherwise, the tested code does no computation at all.</p><p>The details of how this can be implemented are outside the scope of this article now.</p><p>The main idea is that a special Mockito listener can be implemented in order to check that the actual subscribeCount for the publishers returned by the mocked calls is one (the default value in most cases). This is done by intercepting the stubbing lookup when the actual code is executed and returning a PublisherProbe to the tested code instead of the initial publisher, in order to track subscribeCount.</p><p>For the cases when the subscribeCount is indeed 0 or more than 1, the stubbings can be set up to return special publishers which also record the expectedSubscribeCount, in order to actually check it against the actual subscribeCount at the end of the test.</p><p>In the case of JUnit, a new TestRule can be used in order to install this new Mockito listener before a unit test and check the subscribeCount afterwards.</p><p>In the case of TestNG, the BeforeMethod and AfterMethod methods from the UnitTestBase class can be enhanced to do the same thing as the corresponding JUnit rule before and after each test method.</p><p>In the case of Spring integration tests, a new ReactorSubscribeCountTestExecutionListener needs to be implemented, which attaches the Mockito listener in beforeTestMethod() to all the mocks from the application context and then detaches it and checks all subscribe counts in the afterTestMethod() method.</p><h3>Conclusion</h3><p>Clean pure tests need more framework support in order to write them as the tests become more complex:</p><p>When testing pure functions, no special support is needed from the testing framework.</p><p>When writing unit tests, Mockito Strict Stubbing helps with fixing stubbing setup errors faster while writing the tests and also keeps the test setup to the minimum necessary for the test to pass.</p><p>When writing Spring integration tests, the equivalent Strict Stubbing support offers the same benefits in the context of mock objects coming from the application context.</p><p>When writing tests for reactive code, tracking the subscribe count of the returned publishers is needed in order to keep the tests as simple as possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20f1356dee4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Suspend Reactor. Empty Monos are evil]]></title>
            <link>https://medium.com/@andreisilviudragnea/suspend-reactor-empty-monos-are-evil-22930319b15d?source=rss-273c903587eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/22930319b15d</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[reactor]]></category>
            <category><![CDATA[mono]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Andrei Silviu Dragnea]]></dc:creator>
            <pubDate>Mon, 24 Feb 2020 22:27:06 GMT</pubDate>
            <atom:updated>2020-05-07T11:36:59.856Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will talk about the <a href="https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html">Mono</a> reactive publisher from the reactor-core library.</p><p>This abstraction promotes by default a dangerous code style which results in very complex control flow, which obfuscates error conditions disguised as missing values (empty Monos).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uP5ZM3nZ5ASAzv36fpuSig.jpeg" /><figcaption>Reactor core</figcaption></figure><p>To be clear, I am addressing the poor implementation of the Mono publisher only when comparing it to other ways of expressing asynchronous sequential computations, such as Kotlin suspending functions.</p><p>I will use two examples written in Kotlin, one using the Mono API and the other using Kotlin suspending functions, which is functionally equivalent to the first example, especially when it comes to control flow.</p><pre>package com.example<br><br>import reactor.core.publisher.Mono<br><br>fun retrieveAsync(<em>input</em>: String): Mono&lt;String&gt; {<br>    return Mono.empty()<br>}<br><br>fun processAsync(<em>value</em>: String): Mono&lt;String&gt; {<br>    return Mono.just(&quot;processedAsync($<em>value</em>)&quot;)<br>}<br><br>fun computeValueAsync(<em>input</em>: String): Mono&lt;String&gt; {<br>    if (<em>input </em>== &quot;special&quot;) {<br>        return Mono.just(&quot;synchronous&quot;)<br>    }<br>    return <em>retrieveAsync</em>(<em>input</em>)<br>        .flatMap <strong>{ </strong><em>value </em><strong>-&gt; </strong><em>processAsync</em>(<em>value</em>) <strong>}<br></strong>}<br><br>fun main() {<br>    <em>computeValueAsync</em>(&quot;special&quot;)<br>        .doOnSuccess <strong>{ </strong><em>value </em><strong>-&gt; </strong><em>println</em>(<em>value</em>) <strong>}<br>        </strong>.then(<br>            <em>computeValueAsync</em>(&quot;input&quot;)<br>                .doOnSuccess <strong>{ </strong><em>value </em><strong>-&gt; </strong><em>println</em>(<em>value</em>) <strong>}<br>        </strong>)<br>        .block()<br>}</pre><p>The output of the program is</p><pre>synchronous<br>null</pre><p>Telling where the null is coming from in this program is easy because it is small, but any real world reactive program will give you a headache when an unexpected empty Mono shows up.</p><p>The computeValueAsync function either returns a value synchronously in a special case (when input == “special”), or retrieves another value asynchronously, based on the input, then processes it asynchronously before returning the final result.</p><p>The problem with this code is the default behavior of the Mono returned by computeValueAsync, which completes empty if the Mono returned by the retrieveAsync function completes empty. I will present the equivalent code written using Kotlin suspending functions before explaining the code style promoted by Project Reactor’s Monos.</p><pre>package com.example<br><br>import kotlinx.coroutines.runBlocking<br><br>suspend fun retrieve(<em>input</em>: String): String? {<br>    return null<br>}<br><br>suspend fun process(<em>value</em>: String): String? {<br>    return &quot;processedAsync($<em>value</em>)&quot;<br>}<br><br>suspend fun computeValue(<em>input</em>: String): String? {<br>    if (<em>input </em>== &quot;special&quot;) {<br>        return &quot;synchronous&quot;<br>    }<br><br>    val <em>value </em>= retrieve(<em>input</em>)<br><br>    if (<em>value </em>== null) {<br>        return null<br>    }<br>    <br>    return process(<em>value</em>)<br>}<br><br>fun main() = <em>runBlocking </em><strong>{<br>    </strong>val <em>value1 </em>= computeValue(&quot;special&quot;)<br>    <em>println</em>(<em>value1</em>)<br>    val <em>value2 </em>= computeValue(&quot;input&quot;)<br>    <em>println</em>(<em>value2</em>)<br><strong>}</strong></pre><p>For the sake of this example, just imagine that the retrieve(Async) and process(Async) functions really do some asynchronous processing instead of returning a value synchronously.</p><p>The three functions in the example get transformed by having the suspend modifier added to the function signature. The return type gets converted from Mono&lt;String&gt; to String?, because the Mono publisher represents a possibly empty publisher.</p><p>As a side note, please take a look at the main function in both examples, in order to see why Kotlin suspending functions are the perfect programming abstraction for asynchronous sequential computations. The Kotlin code, apart from the suspend modifier and the runBlocking coroutine builder, which bridges the asynchronous and synchronous worlds, looks exactly like blocking code, because asynchrony is a cross-cutting concern which should not make writing code more difficult and obfuscate the essential business logic (those nasty ifs).</p><p>The real problem here is the short-circuit of the control flow in the computeValue function if the retrieved value is null, because this is how the flatMapoperator works <em>by default</em>.</p><p>Any experienced developer reading code like in the suspending functions example should immediately raise a flag about silently propagating emptiness in the control flow of the application.</p><p>Real world reactive code builds way more complex reactive pipelines than the one in this example. By only adding two more .flatMap calls after the .flatMap { value -&gt; processAsync(value) } step brings two more null guards which short-circuit the flow of the equivalent computeValue function.</p><p>Bring in the asynchronous code stack from Project Reactor (which can be seen using Reactor debugging facilities, but not very helpful for emptiness propagation) and one empty Mono somewhere down the async call stack will wreak havoc. Most of your reactive pipeline will not execute at all, apart from the operators handling emptiness. The points which handle emptiness are usually too far away from where the emptiness emerged. This situation is also undebuggable in the Project Reactor scenario, because there is no place to put a breakpoint in order to see where the disguised null is coming from.</p><p>In the code of the second example, if it were written in “suspending” Java, because in Java we are allowed to forget checking for nullness, a NullPointerException would have occurred. In my opinion, a NPE is way more desirable either in production or test scenarios, because it immediately tells you that there is a bug in your code and it is easy to spot the source of the null value, because the exception occurs next to its source.</p><p>In the suspending Kotlin example, by making you think about nullability from the beginning, maybe designing your code to never return a nullable value from the `retrieve()` method is a better alternative altogether.</p><p>The problem of the Mono implementation is that it allows empty Monos to bypass operators like flatMap when the Mono completes empty, when instead an EmptinessPropagationException should have been thrown in that case. I have seen this programming pattern abused in Spring Security 5, where at the end of a complex reactive pipeline, there is a switchIfEmpty handler which maps any unexpected emptiness to an exception.</p><p>A Mono which unexpectedly completes empty is a programming bug. When it happens (and it will happen), the hidden control flow of the reactive code makes it very hard to debug. I believe that the Mono publisher should have had operators like flatMap not accepting emptiness <em>by default</em> and a different set of operators for valid empty Mono scenarios, like nullableFlatMap, whose lambda argument can receive a nullable value. The suggested setup does not violate the Reactive Streams specification of not propagating null data signals, because this nullness handling would be internal to the operator implementation (not executing the lambda on nullableFlatMap until the .onComplete signal comes), which is out of the Reactive Streams specification.</p><p>But given the current state of things, I have tried using a hook in our codebase, during tests, which replaces, for example, the implementation of the flatMap operator with a variant which propagates anEmptinessPropagationException if the Mono above the flatMapcompletes empty. The purpose of this hook is to reify emptiness and explicitly handle it, instead of propagating it further. The refactored code of the first scenario looks like this:</p><pre>fun computeValueAsync(<em>input</em>: String): Mono&lt;String&gt; {<br>    if (<em>input </em>== &quot;special&quot;) {<br>        return Mono.just(&quot;synchronous&quot;)<br>    }<br>    return <em>retrieveAsync</em>(<em>input</em>)<br>        .map <strong>{ </strong><em>value </em><strong>-&gt; </strong>Optional.of(<em>value</em>) <strong>}<br>        </strong>.switchIfEmpty(Mono.just(Optional.empty()))<br>        .flatMap <strong>{ </strong><em>value </em><strong>-&gt; </strong><em>processAsync</em>(<em>value</em>.get()) <strong>}<br></strong>}</pre><p>The flatMap operator now processes an Optional value and the failure of handling emptiness is now very easy to spot, as the .get() call will throw a NoSuchElementException for empty Optionals. Basically, in order to avoid the default emptiness propagation behavior of almost all Mono operators, you have to wrap the value of the Mono inside an Optional, in order to reify emptiness, as in the example above (an Optional-wrapping operator can be useful here. In Kotlin, an extension function saves us. In Java, not so easy, only maybe using the transform operator). You can also choose to place a guard .switchIfEmpty(Mono.error(EmptinessPropagationException())) operator before each operator which propagates emptiness.</p><p>The reason why I looked so much into the actual control flow of reactive programs is because I am working on an Intellij plugin which automatically converts Java code written using Project Reactor to suspending Kotlin code, by first converting Java code to Kotlin using the embedded nj2k compiler from Intellij IDEA and then processing the Kotlin code in my plugin to get rid of the reactive pipeline. To my surprise, keeping the code functionally equivalent emphasizes the complex control flow masked by the reactive operators.</p><p>I will come with more articles like this on my journey from Reactive Streams (Project Reactor for now) to Kotlin suspending functions and Flows. I have discovered more bad programming patterns like this, which are easy to misuse <em>by default </em>when using Project Reactor.</p><p><a href="https://medium.com/u/4762e889f8fc">Roman Elizarov</a> might be interested in this article, because it is a good example of Kotlin suspending functions in action, promoting simple and easy to understand control flow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22930319b15d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>