<?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 Nelson Wright on Medium]]></title>
        <description><![CDATA[Stories by Nelson Wright on Medium]]></description>
        <link>https://medium.com/@nelson-wright?source=rss-e9bd64af9f2d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JP34gdpuLPHmhl8nAd1wzw.jpeg</url>
            <title>Stories by Nelson Wright on Medium</title>
            <link>https://medium.com/@nelson-wright?source=rss-e9bd64af9f2d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:03:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nelson-wright/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[An experience of unit testing with the Arrange, Act, Assert (AAA) pattern: Part II]]></title>
            <link>https://nelson-wright.medium.com/an-experience-of-unit-testing-with-the-arrange-act-assert-aaa-pattern-part-ii-5cee988654ab?source=rss-e9bd64af9f2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cee988654ab</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[experience]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Nelson Wright]]></dc:creator>
            <pubDate>Mon, 18 May 2020 19:19:56 GMT</pubDate>
            <atom:updated>2021-04-20T16:54:56.153Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Recap</strong>: in <a href="https://medium.com/@nelson.wright/an-experience-of-unit-testing-with-the-arrange-act-assert-aaa-pattern-part-i-53babd01c52b">Part I</a>, we looked at some “rules” we used to apply the “Arrange, Act, Assert” (AAA) pattern. In this part, we’ll look at some nuances, and how it sometimes highlighted issues in either the production or test code.</p><h3>Phase labels</h3><p>At the end of <a href="https://medium.com/@nelson.wright/an-experience-of-unit-testing-with-the-arrange-act-assert-aaa-pattern-part-i-53babd01c52b">Part I</a>, we were considering this larger test:</p><pre>@Test<br><strong>fun </strong>shouldReverseStringInput() {<br>    <em>// arrange<br>    </em><strong>val </strong>exclaim = <strong>&quot;!!&quot;<br>    val </strong>firstInput = <strong>&quot;cba&quot;<br>    val </strong>secondInput = <strong>&quot;gfed&quot;<br>    val </strong>compoundInput = <strong>&quot;$</strong>exclaim<strong>$</strong>secondInput<strong>$</strong>firstInput<strong>&quot;<br><br>    val </strong>expectedReversedString = <strong>&quot;abcdefg!!&quot;<br><br>    </strong><em>//act<br>    </em><strong>val </strong>result = compoundInput.<em>reversed</em>()<br><br>    <em>//assert<br>    </em>assertThat(result).isEqualTo(expectedReversedString)<br>}</pre><p>Although we can see where the three phases start and end, we should heed the words of <a href="https://blog.ploeh.dk/2013/06/24/a-heuristic-for-formatting-code-according-to-the-aaa-pattern/">Mark Seeman</a>:</p><blockquote>Whenever I need to add code comments to indicate the three AAA phases, an alarm goes off in my head. Something is wrong; the test is too complex. It would be better if I could refactor either the test or the SUT to become simpler.</blockquote><p>It’s worth repeating that this could be either the test code <strong>or</strong> the <a href="https://en.wikipedia.org/wiki/System_under_test">SUT</a>. If you find yourself with an overly chunky test, then it’s worth looking at the SUT, to see if that gives any clues as to why.</p><h3>Simplify?</h3><p>At times it’s tempting to try and “simplify” the test by <a href="https://refactoring.com/catalog/extractFunction.html">extracting some of it</a> into a separate method:</p><pre>@Test<br><strong>fun </strong>shouldReverseStringInput() {<br>    <strong>val </strong>compoundInput = createCompoundInput()<br>    <strong>val </strong>expectedReversedString = <strong>&quot;abcdefg!!&quot;<br>    <br>    val </strong>result = compoundInput.<em>reversed</em>()<br>    <br>    assertThat(result).isEqualTo(expectedReversedString)<br>}<br><br><strong>private fun </strong>createCompoundInput(): String {<br>    <strong>val </strong>exclaim = <strong>&quot;!!&quot;<br>    val </strong>firstInput = <strong>&quot;cba&quot;<br>    val </strong>secondInput = <strong>&quot;gfed&quot;<br>    val </strong>compoundInput = <strong>&quot;$</strong>exclaim<strong>$</strong>secondInput<strong>$</strong>firstInput<strong>&quot;<br>    return </strong>compoundInput<br>}</pre><p>We found that for our team, usually this wasn’t a good idea. It makes it harder to see the relationship between the actual and expected results in the assert phase. Plus, it doesn’t really simplify the test, it just adds indirection. With a modern IDE one could argue it’s only a click away, but it all adds to the cognitive load. And if it’s complicated to set up the data for a test, then perhaps the SUT is doing too much, and is too complex.</p><p>Sometimes though, we found ourselves repeating the same lines for a significant number of the tests. In these cases, wouldn’t extracting a common method be better?</p><p>Perhaps. If it’s in the “Arrange” phase, it could possibly be an indication that there’s another class that could be extracted from the SUT. Once again, there’s a possibility the SUT is doing too much.</p><p>If it’s in the “Assert” phase, then we need to be mindful of what <a href="https://wiki.c2.com/?ArrangeActAssert">Jeff Grigg warned us about</a>:</p><blockquote>Test methods that try to test too many different things at once.</blockquote><p>We’ll add this caveat while we’re on this topic, <a href="https://softwareengineering.stackexchange.com/questions/7823/is-it-ok-to-have-multiple-asserts-in-a-single-unit-test?newreg=1128976a911144b7932aebf84ce45c1d">as outlined by Roy Osherove</a>:</p><blockquote>My guideline is usually that you test one logical CONCEPT per test. You can have multiple asserts on the same <em>object</em>. They will usually be the same concept being tested.</blockquote><p>We did sometimes have methods in our code which had multiple asserts on properties of the same object. It’s a bit more indirection, but with careful naming of the method, it can be manageable.</p><p>However, we also tolerated a little more repetition in our tests than we would do in our production code. For example we wouldn’t always extract two identical assert lines repeated two or three times. It’s a trade-off between readability/ease of understanding of an individual unit test, and making the test code <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>.</p><p>Did we have some larger tests with the phase labels? We did, but not very many. For example, some older legacy classes that we were planning on changing to a different architecture in future. Your mileage may vary, but we felt that we could live with the occasional chunky test for older code.</p><h4>Multiple “Act” lines?</h4><p>When we first started writing unit tests, we would sometimes have multiple lines in the “Act” phase, although not usually more than two. Over time, we tended to view this as something undesirable. If the goal of a unit test is to test one logical concept, then having two or more “Act” lines doesn’t fit that notion too well.</p><p>For example, say we have a test on a repository class, to ensure we use the cached data, and don’t make another http request:</p><pre>@Test<br><strong>fun </strong>shouldUseCachedData() {<br>    <em>// some setup in the &quot;Arrange&quot; phase here, which we&#39;ll<br>    // leave out for the sake of simplicity<br>    <br>    </em>repository.makeARequestForData()<br>    repository.makeARequestForData()<br><br>    <em>verify</em>(exactly = 1) <strong>{ </strong>repository.makeHttpRequestToApi() <strong>}<br></strong>}</pre><p><em>(Note: I’m using </em><a href="https://mockk.io/"><em>Mockk</em></a><em> here for the verification, but hopefully the intention in this simplified test is clear)</em></p><p>The first repository.makeARequestForData() line will make the call to the makeHttpRequestToApi() method, which makes it feel a bit like an <strong>Act</strong>ion, so it’s tempting to put it in the “Act” phase.</p><p>However, this is really a way for us to set the data in the SUT in a convenient way, which makes sense in the context of this test. So, as it’s part of the setup of this test, it should go into the “Arrange” phase instead. The second repository.makeARequestForData() line is the real “Act” line. We could also amend the test method name to better reflect what we’re testing:</p><pre>@Test<br><strong>fun </strong>shouldNotMakeSecondCallToApiIfDataCached() {<br>    <em>// some setup in the &quot;Arrange&quot; phase here, which we&#39;ll<br>    // leave out for the sake of simplicity<br>    </em>repository.makeARequestForData()<br>    <br>    repository.makeARequestForData()<br><br>    <em>verify</em>(exactly = 1) <strong>{ </strong>repository.makeHttpRequestToApi() <strong>}<br></strong>}</pre><p>We found that it’s worth pondering what you’re really testing. It’s also possible that the unit test could be broken into two (or more) tests if you find it’s tempting to have multiple “Act” lines.</p><h3>AAA with TDD</h3><p>How well does AAA play with <a href="https://en.wikipedia.org/wiki/Test-driven_development">Test-Driven Development</a>? We found it works very well. As Jeff Griggs mentioned in <a href="https://medium.com/@nelson.wright/an-experience-of-unit-testing-with-the-arrange-act-assert-aaa-pattern-part-i-53babd01c52b">Part I</a>, it “Clarifies and focuses attention”. In this case, on the different phases.</p><h4>Assert First</h4><p>As <a href="https://vance.com/">Steve Vance</a> once advised me, it’s often a good idea to start with the “Assert” phase when writing a unit test. I tend to view it as a visible destination for the test. But maybe you’re at the point where you haven’t even created the SUT in code. That’s OK, you can write in pseudocode what you want to prove in the test. Nothing will compile yet, but that’s fine. You’d then work back to the “Act”, and consider what you’d do to achieve the situation you’re asserting. Then, think about the setup in the “Arrange” phase, although often that will become more evident as you implement the test anyway. So you might initially write something like:</p><pre>@Test<br><strong>fun </strong>shouldInitialiseSearchUseCase() {<br>    assertThat(searchUseCase has been initialised with location)<br>}</pre><p>then thinking about the “Act” phase, you may decide to go with passing in an object to an initialise() method:</p><pre>@Test<br><strong>fun </strong>shouldInitialiseSearchUseCase() {<br>    searchUseCase.initialise(initialData)<br><br>    assertThat(searchUseCase has been initialised with location)<br>}</pre><p>then finally the setup pseudocode in the “Arrange” phase:</p><pre>@Test<br><strong>fun </strong>shouldInitialiseSearchUseCase() {<br>    mock fake user location<br>    create initialData object<strong> </strong>which includes user location<br><br>    searchUseCase.initialise(initialData)<br><br>    assertThat(searchUseCase has been initialised with location)<br>}</pre><p>Then, start to implement each phase, once again starting with the “Assert” phase, and working back through “Act” to “Arrange”. We found breaking the process of writing tests down into the phases in this way could be helpful. Whether writing with pseudocode or real code.</p><h3>Guard Asserts</h3><p><a href="https://wiki.c2.com/?GuardClause">Guard clauses</a> in production code are often useful. What about assertions in test code, but not in the “Assert” phase? For example, used to check that some data is in a certain state, before proceeding:</p><pre>@Test<br><strong>fun </strong>shouldNotMakeSecondCallToApiIfDataCached() {<em><br>    </em>repository.makeARequestForData()<br>    <strong>assertThat(repository.hasData()).isTrue</strong>    <br>    <br>    repository.makeARequestForData()<br><br>    <em>verify</em>(exactly = 1) <strong>{ </strong>repository.makeHttpRequestToApi() <strong>}<br></strong>}</pre><p>In our team we tended not to view these too favourably. It can make it harder to quickly eyeball the test, as there appears to be multiple “Assert” phases. Also, our thinking was that as this code is running in a test environment, we should really have control over how the test data is created. If we don’t, then that could indicate other problems in the test code. Perhaps we haven’t mocked a collaborating object correctly. Perhaps we haven’t scheduled <a href="https://developer.android.com/reference/android/arch/core/executor/testing/InstantTaskExecutorRule">tasks to run synchronously</a>.</p><p>Of course, if a test crashes at some point due to an unforeseen error, you won’t get as nice an error message as you would with a guard assert. But hopefully your unit tests don’t crash too often. When ours sometimes did, we found the stack trace tended to pinpoint the error anyway.</p><p>For our team, a test crashing for an obscure reason was a rare occurrence. So we thought the trade-off of less noise in the tests, by having no guard asserts, was one we were happy to make.</p><h3>Conclusion</h3><p>On our team, we found it helpful to have the unit tests structured in the Arrange, Act and Assert phases. It made the tests easier to read and understand. At times, it could highlight issues in either the production code or the test code. We didn’t find there to be any significant downsides in using the pattern.</p><p>One minor issue was having to explain it to new team members. To overcome that, we incorporated it into our onboarding process for all developers joining the team.</p><p><em>I’m interested in whether your team uses this pattern, and if so, whether it works for you. Let me know in the comments!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cee988654ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An experience of unit testing with the Arrange, Act, Assert (AAA) pattern: Part I]]></title>
            <link>https://medium.com/swlh/an-experience-of-unit-testing-with-the-arrange-act-assert-aaa-pattern-part-i-53babd01c52b?source=rss-e9bd64af9f2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/53babd01c52b</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[experience]]></category>
            <dc:creator><![CDATA[Nelson Wright]]></dc:creator>
            <pubDate>Mon, 18 May 2020 19:19:18 GMT</pubDate>
            <atom:updated>2023-07-21T07:23:11.129Z</atom:updated>
            <content:encoded><![CDATA[<p>For the last 6 years I’ve been part of an Android team doing a lot of unit testing, usually with TDD. This is how we’ve been using the “Arrange, Act, Assert” (AAA) pattern as part of our daily routine, and what worked for us.</p><p>The AAA pattern for structuring unit tests has been around for a while now. This part (Part I) sets out what our team did in practice, to apply this pattern. <a href="https://medium.com/@nelson.wright/an-experience-of-unit-testing-with-the-arrange-act-assert-aaa-pattern-part-ii-5cee988654ab">Part II</a> explores some nuances, including how at times it highlighted issues in our code.</p><h3>Why do it at all?</h3><p>Jeff Griggs enumerates the benefits of AAA in <a href="https://wiki.c2.com/?ArrangeActAssert">this succinct wiki article</a>:</p><blockquote>Clearly separates what is being tested from the setup and verification steps.</blockquote><blockquote>Clarifies and focuses attention on a historically successful and generally necessary set of test steps.</blockquote><blockquote><strong>Makes some Test Smells more obvious:</strong></blockquote><blockquote>Assertions intermixed with “Act” code.</blockquote><blockquote>Test methods that try to test too many different things at once.</blockquote><p>The pattern was <a href="https://xp123.com/articles/3a-arrange-act-assert/">observed and named by Bill Wake</a> in 2001. Microsoft continue to use it, for example in this <a href="https://docs.microsoft.com/en-us/visualstudio/test/unit-test-basics?view=vs-2019">Unit Test Basics</a> article from 2019. There’s also various articles here on Medium, and elsewhere.</p><p>So, everyone must know about this by now, right?</p><p>I had thought so. But then a Tech Lead friend at a global company told me that when he joined, most of the developers there had not heard of the pattern. And partly as a result of that, the tests were hard to read and understand. Then I recalled that every developer who’d joined our team hadn’t heard of it either.</p><p>It’s a very simple concept to understand, but there are some interesting questions around its use. Overall, we found it useful in our unit tests, in just the way Jeff Griggs describes above. We’ve retained the practice since it’s inception over six years ago.</p><h3>The Rules</h3><p>This is what our team adopted as the “rules” when formatting tests, as <a href="https://blog.ploeh.dk/2013/06/24/a-heuristic-for-formatting-code-according-to-the-aaa-pattern/">outlined by Mark Seemann</a>:</p><ol><li>If the test is 3 lines or less, there’s no need for blank lines between the phases.</li><li>If the test is more than 3 lines, then have a blank line between the phases, i.e. one blank line either side of the “Act” line.</li><li>If the test is sufficiently complex that having a blank line within any of the three phases is beneficial, then a comment line labelling each phase should also be used.</li></ol><p>That’s all fine and well, but it does give rise to some questions. Lets take a look at those next, with some examples.</p><h3>3 lines or less</h3><p>If we take a Kotlin version of Jeff Grigg’s example test, we can have:</p><pre>@Test<br><strong>fun </strong>shouldReverseStringInput() {<br>    <strong>val </strong>input = <strong>&quot;abc&quot;<br>    val </strong>result = input.<em>reversed</em>()<br>    assertThat(result).isEqualTo(<strong>&quot;cba&quot;</strong>)<br>}</pre><p>(<em>Note: we wouldn’t normally test the Kotlin language feature </em><strong><em>reversed()</em></strong><em>, but this is just for illustration purposes. I’ve also used </em><a href="https://assertj.github.io/doc/"><em>assertj</em></a><em> for the assertions, as I find it more readable.</em>)</p><p>That’s all fine, we’ve got 3 lines in the test method, matching the three phases of Arrange, Act, and Assert. What happens though, if we inline the input val?</p><pre>@Test<br><strong>fun </strong>shouldReverseStringInput() {<br>    <strong>val </strong>result = <strong>&quot;abc&quot;</strong>.<em>reversed</em>()<br>    assertThat(result).isEqualTo(<strong>&quot;cba&quot;</strong>)<br>}</pre><p>How do we now know what are the stages in the test? The thinking is that as it’s a very simple test (2 lines), it should be fairly self-evident. And, looking at the test, there doesn’t seem to be any ambiguity that</p><p><strong>val </strong>result = <strong>“abc”</strong>.<em>reversed</em>()</p><p>is the “Act” line. There isn’t a separate “arrange” phase now, as we’re performing an <strong>Act</strong>ion directly on the abc string literal.</p><p>What would happen if we then inlined the result val?</p><pre>@Test<br><strong>fun </strong>shouldReverseStringInput() {<br>    assertThat(<strong>&quot;abc&quot;</strong>.<em>reversed</em>()).isEqualTo(<strong>&quot;cba&quot;</strong>)<br>}</pre><p>We’re left with a test with just an “Assert” phase, with the assertThat line. The “Act” part is embedded. That can be OK, as long as it’s still readable. Whether it is or not, is up to you and your team. The goal is readable, understandable tests, after all. We want to avoid ultra-dense tests that take time to understand if they fail in say, 3 months time.</p><h3>More than 3 lines</h3><p>What happens if we have more than three lines? Say we extract the &quot;cba”string literal to a val with a hopefully more meaningful name:</p><pre>@Test<br><strong>fun </strong>shouldReverseStringInput() {<br>    <strong>val </strong>input = <strong>&quot;abc&quot;<br>    val </strong>expectedReversedString = <strong>&quot;cba&quot;<br><br>    val </strong>result = input.<em>reversed</em>()<br><br>    assertThat(result).isEqualTo(expectedReversedString)<br>}</pre><p>As we’ve now got more than 3 lines, the second rule comes into effect, so we now have a blank line to separate the phases. This makes the “Act” stand out well, and it’s clear where the other phases start and end. So far, so good.</p><p>What happens if more lines are added?</p><p>Say we want to do some more setup in the “Arrange” phase. We want to join three strings, and reverse that compound string:</p><pre>@Test<br><strong>fun </strong>shouldReverseStringInput() {<br>    <strong>val </strong>exclaim = <strong>&quot;!!&quot;<br>    val </strong>firstInput = <strong>&quot;cba&quot;<br>    val </strong>secondInput = <strong>&quot;gfed&quot;<br>    val </strong>compoundInput = <strong>&quot;$</strong>exclaim<strong>$</strong>secondInput<strong>$</strong>firstInput<strong>&quot;<br>    val </strong>expectedReversedString = <strong>&quot;abcdefg!!&quot;</strong></pre><pre><strong>    val </strong>result = compoundInput.<em>reversed</em>()<br><br>    assertThat(result).isEqualTo(expectedReversedString)<br>}</pre><p>We can still see the phases, but perhaps it would aid understanding if there was a blank line before the expectedReversedStringline, to separate the setting up of the input and the result variables:</p><pre>@Test<br><strong>fun </strong>shouldReverseStringInput() {<br>    <strong>val </strong>exclaim = <strong>&quot;!!&quot;<br>    val </strong>firstInput = <strong>&quot;cba&quot;<br>    val </strong>secondInput = <strong>&quot;gfed&quot;<br>    val </strong>compoundInput = <strong>&quot;$</strong>exclaim<strong>$</strong>secondInput<strong>$</strong>firstInput<strong>&quot;<br>    <br>    val </strong>expectedReversedString = <strong>&quot;abcdefg!!&quot;<br><br>    val </strong>result = compoundInput.<em>reversed</em>()<br><br>    assertThat(result).isEqualTo(expectedReversedString)<br>}</pre><p>Now it’s not quite so easy to scan the test quickly and identify the phases. This would likely only increase if the test became more complex. We should use Rule 3, and label the three phases with a comment:</p><pre>@Test<br><strong>fun </strong>shouldReverseStringInput() {<br>    <em>// arrange<br>    </em><strong>val </strong>exclaim = <strong>&quot;!!&quot;<br>    val </strong>firstInput = <strong>&quot;cba&quot;<br>    val </strong>secondInput = <strong>&quot;gfed&quot;<br>    val </strong>compoundInput = <strong>&quot;$</strong>exclaim<strong>$</strong>secondInput<strong>$</strong>firstInput<strong>&quot;<br><br>    val </strong>expectedReversedString = <strong>&quot;abcdefg!!&quot;<br><br>    </strong><em>//act<br>    </em><strong>val </strong>result = compoundInput.<em>reversed</em>()<br><br>    <em>//assert<br>    </em>assertThat(result).isEqualTo(expectedReversedString)<br>}</pre><p>There’s a slight downside in that it increases the size of the test in terms of the total number of lines. However, adding the comments doesn’t increase the cognitive load in trying to understand it.</p><p>Those are the basic “rules”. It’s probably becoming clear that if we have a more complex test that requires the labelling above, it isn’t always easy to read. Even with the labels.</p><p>So, with that in mind, let’s take a look next at what using this pattern can tell us about our code.</p><h3>Continue Reading</h3><p><a href="https://medium.com/@nelson.wright/an-experience-of-unit-testing-with-the-arrange-act-assert-aaa-pattern-part-ii-5cee988654ab">An experience of unit testing with the Arrange, Act, Assert (AAA) pattern: Part II</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53babd01c52b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/an-experience-of-unit-testing-with-the-arrange-act-assert-aaa-pattern-part-i-53babd01c52b">An experience of unit testing with the Arrange, Act, Assert (AAA) pattern: Part I</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>