<?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"><channel><title><![CDATA[Policiano]]></title><description><![CDATA[Policiano]]></description><link>https://policiano.com</link><generator>RSS for Node</generator><lastBuildDate>Thu, 10 Sep 2026 10:20:06 GMT</lastBuildDate><atom:link href="https://policiano.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How do I name my test methods?]]></title><description><![CDATA[Hello there! It's great to be back here, ready to dive into unit testing again. Today, I want to share some valuable techniques that I personally use to give effective names to my unit test methods. Naming things can be a challenge for many developer...]]></description><link>https://policiano.com/how-do-i-name-my-test-methods</link><guid isPermaLink="true">https://policiano.com/how-do-i-name-my-test-methods</guid><category><![CDATA[Testing]]></category><category><![CDATA[unit testing]]></category><category><![CDATA[Swift]]></category><category><![CDATA[iOS]]></category><category><![CDATA[clean code]]></category><dc:creator><![CDATA[Will Policiano]]></dc:creator><pubDate>Sat, 29 Oct 2022 20:02:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/Pll7AP6NFpY/upload/v1667074653746/pTNWX4f5FK.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello there! It's great to be back here, ready to dive into unit testing again. Today, I want to share some valuable techniques that I personally use to give effective names to my unit test methods. Naming things can be a challenge for many developers, including myself. Whether it's classes, variables, functions, or methods, finding the right name often requires some extra thought. And when it comes to unit tests, this challenge becomes even more apparent.</p>
<h1 id="heading-the-problem">The Problem</h1>
<p>I've found myself spending more time brainstorming a good name for my test than actually writing the test itself. It's essential to strike a <strong>balance between expressing the test's intent and keeping the name concise and easy to read</strong>. After all, when someone reviews your code or looks at the CI log, they want to understand the test's purpose quickly. So, in this post, I'll share some techniques that may come in handy when you face this naming dilemma.</p>
<p>But before we get into the techniques, let's talk about some conventions and patterns that can make your test names more consistent and comprehensible, especially when working in larger teams.</p>
<h1 id="heading-conventions-and-patterns">Conventions and Patterns</h1>
<p>To start, it's helpful to establish a consistent pattern or template for naming your test methods. Having a standardized format benefits everyone involved. It enables developers to understand each other's code more easily and write new code faster. Here are a couple of aspects to consider</p>
<h2 id="heading-line-length">Line length</h2>
<p>Nobody enjoys scrolling horizontally through code, especially during code reviews or when reading a CI log. So, I strongly recommend setting a maximum line length for your method names. Long test names can be a sign of underlying issues, such as complex setups or obscure conditions. It's an opportunity to reassess the design of the subject being tested.</p>
<p>You can choose a suitable line length for your project, but I suggest aiming for a range between 90 and 130 characters. This ensures that your test names fit comfortably on a GitHub page without requiring line breaks or horizontal scrolling. To make it easier to adhere to this restriction, you can enable the page guide in your editor. In Xcode, go to <code>Xcode &gt; Preferences &gt; Text Editing</code> and check the "Page guide column" option.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667077328331/jm2cgDzrC.png" alt="Enable page guide checkbox" /></p>
<p>Once enabled, the page guide will be visible in your editor, helping you stay within the desired line length.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667077510294/MCyLZbhoR.png" alt="Page guide being shown on code editor" class="image--center mx-auto" /></p>
<h2 id="heading-formatting">Formatting</h2>
<p>Deciding on a consistent format for your test names is crucial. You can choose from lowercase, uppercase, camel-case, or snake-case—whatever works best for your project. Personally, I start my test names with the <code>test_</code> prefix.</p>
<p>It's also helpful to adopt a specific casing pattern for your method names. I prefer using lower-camel case, where each word starts with a lowercase letter except for the first word. Here's an example to illustrate the point:</p>
<p>✅ Do:</p>
<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_deselectsItemUponSecondTap</span><span class="hljs-params">()</span></span>
</code></pre>
<p>🛑 Don’t:</p>
<pre><code class="lang-swift"><span class="hljs-comment">// Doesn't have the defined underscore</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">testDeselectItemUponSecondTap</span><span class="hljs-params">()</span></span>
</code></pre>
<pre><code class="lang-swift"><span class="hljs-comment">// Snake case</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_deselect_item_upon_second_tap</span><span class="hljs-params">()</span></span>
</code></pre>
<pre><code class="lang-swift"><span class="hljs-comment">// Mixed cases</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_deselectItem_uponSecondTap</span><span class="hljs-params">()</span></span>
</code></pre>
<p>You might wonder why I recommend adding an underscore (_) after the <code>test</code> prefix. This practice serves a specific purpose—to separate the <code>test</code> keyword from the test's intent, which will be explained in more detail in the next section.</p>
<p>By introducing this visual separation, we create a clearer distinction between the standardized <code>test</code> prefix and the descriptive part of the test name. It enhances readability and makes it easier for developers to quickly identify that a method is a test method.</p>
<p>Once you've established these conventions and patterns, you're ready to move on to the next step.</p>
<h1 id="heading-expressive-test-summaries"><strong>Expressive Test Summaries</strong></h1>
<p>A well-crafted test name should provide a concise summary of what is being tested. This is the most challenging part, but here's a useful approach to consider. Imagine you're writing a commit message, and try to complete the following sentence:</p>
<ul>
<li><em>"This test ensures that the SUT (System Under Test) ...</em></li>
</ul>
<p>Let me give you a few examples:</p>
<p><em>... deselects an item upon a second tap."</em></p>
<p><em>... shows content on a successful response."</em></p>
<p><em>... returns the preferred payment method."</em></p>
<p><em>... completes with a not-found error on invalid URLs."</em></p>
<p>Keep it simple. Just complete the sentence using the Simple Present tense. By doing this, you focus on the behavior or functionality of the SUT without including details about spies, collaborators, class names, or implementation specifics. This approach makes your tests more flexible when it comes to refactoring.</p>
<p>To comply with the line length restrictions, you may need to omit some article words. Remember, the goal is to create test summaries that are clear and concise.</p>
<p>✅ Do:</p>
<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_showsContentOnSuccessfulResponse</span><span class="hljs-params">()</span></span>
</code></pre>
<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_returnsPreferredPaymentMethod</span><span class="hljs-params">()</span></span>
</code></pre>
<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_completesWithNotFoundErrorOnInvalidURLs</span><span class="hljs-params">()</span></span>
</code></pre>
<p>🛑 Don’t:</p>
<pre><code class="lang-swift"><span class="hljs-comment">// Unecessary verbosity</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_givenASuccessfulResponseWhenTheScreenAppearShouldShowSomeContent</span><span class="hljs-params">()</span></span>
</code></pre>
<pre><code class="lang-swift"><span class="hljs-comment">// Past tense</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_returnedPreferedPayment</span><span class="hljs-params">()</span></span>
</code></pre>
<pre><code class="lang-swift"><span class="hljs-comment">// Too coupled with implementation details</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test_completesWith404ErrorFromTheNetworkingForURLRequestsWithInvalidURLs</span><span class="hljs-params">()</span></span>
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<p>These are some of the standards and techniques that have proven effective in my unit tests. They have greatly helped both my team and me, and I hope they can do the same for you. Of course, keep in mind that this post reflects my personal opinions and experiences, so feel free to adapt these techniques to fit your specific context. Thank you for taking the time to read this post! Until next time!</p>
]]></content:encoded></item><item><title><![CDATA[Make your tests cleaner using the Fixture Pattern]]></title><description><![CDATA[Every unit test has an arrangement step where we set up the test preconditions. In this step, we often need to provide some input objects to the subject under test.
Providing these objects can become pretty verbose and painful to write. Let's see som...]]></description><link>https://policiano.com/2022-02-01-make-your-tests-cleaner-using-the-fixture-pattern</link><guid isPermaLink="true">https://policiano.com/2022-02-01-make-your-tests-cleaner-using-the-fixture-pattern</guid><category><![CDATA[Testing]]></category><category><![CDATA[clean code]]></category><category><![CDATA[Swift]]></category><category><![CDATA[iOS]]></category><category><![CDATA[design patterns]]></category><dc:creator><![CDATA[Will Policiano]]></dc:creator><pubDate>Wed, 02 Feb 2022 02:07:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1643766797378/dzxddSzavN.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Every unit test has an <strong>arrangement</strong> step where we set up the test preconditions. In this step, we often need to provide some input objects to the <a target="_blank" href="http://xunitpatterns.com/SUT.html"><em>subject under test</em></a>.</p>
<p>Providing these objects can become pretty verbose and painful to write. Let's see some example:</p>
<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">testValidateOrder_deliversErrorOnEmptyOrder</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> emptyItems: [<span class="hljs-type">Item</span>] = []
    <span class="hljs-keyword">let</span> anySeller = <span class="hljs-type">Seller</span>(uuid: <span class="hljs-string">"any UUID"</span>, name: <span class="hljs-string">"any name"</span>, websiteUrl: <span class="hljs-type">URL</span>(string: <span class="hljs-string">"http://any-url.com"</span>)!)
    <span class="hljs-keyword">let</span> order = <span class="hljs-type">Order</span>(uuid: <span class="hljs-string">"any UUID"</span>, date: <span class="hljs-type">Date</span>(), items: emptyItems, totalPrice: <span class="hljs-number">0.0</span>, discount: <span class="hljs-number">0.0</span>, seller: anySeller)

    <span class="hljs-keyword">let</span> actualResult = sut.validate(order: order)

    <span class="hljs-type">XCTAssertEqual</span>(actualResult, <span class="hljs-type">OrderValidationError</span>.emptyOrder)
}
</code></pre>
<p>This is a simple method that validates an order. In this case, orders without items are not allowed and are expected to return an error.
Look how verbose and hard to understand this method became. The cause of it is the complexity of the arrangement. To perform the <code>validate(order:)</code> we need to create an <code>Order</code>, which is not a trivial object. Also, the <code>Order</code> object is not an <a target="_blank" href="https://martinfowler.com/bliki/TestDouble.html">test double</a> but an actual system object type.</p>
<p>Therefore, to improve it, we need to make our test cleaner and focused on what matters by abstracting the object creation and simplifying the arrangement step. We can do it with <strong>Fixtures</strong>.</p>
<h1 id="heading-fixtures">Fixtures</h1>
<p>Before all, compare the previous example with this new one:</p>
<pre><code class="lang-swift"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">testValidateOrder_deliversErrorOnEmptyOrder</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">let</span> order = <span class="hljs-type">Order</span>.fixture(items: [])

    <span class="hljs-keyword">let</span> actualResult = sut.validate(order: order)

    <span class="hljs-type">XCTAssertEqual</span>(actualResult, <span class="hljs-type">OrderValidationError</span>.emptyOrder)
}
</code></pre>
<p>Much cleaner, uh?
I could abstract the <code>Order</code> creation and focus on what really matters: Setting up an empty order.</p>
<p>This kind of abstraction is called <strong>fixture</strong> and we can find a great formal definition for test fixtures on the <a target="_blank" href="https://github.com/junit-team/junit4/wiki/Test-fixtures">JUnit 4</a> documentation:</p>
<blockquote>
<p>A fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is <strong>to ensure that there is a well-known and fixed environment</strong> in which tests are run so that results are repeatable.</p>
</blockquote>
<p>In other words, a fixture is a good way to ensure good code readability on abstracting objects creation. Let's see how to implement it in Swift.</p>
<h1 id="heading-implementing-a-fixture">Implementing a Fixture</h1>
<p>Because creating fixtures is related to testing purposes, it's recommended to implement it in the Test target. I will use this file naming:</p>
<pre><code class="lang-txt">Order+Fixtures.swift
</code></pre>
<p>Now we can add extensions to our objects and create the fixture this way:</p>
<pre><code class="lang-swift"><span class="hljs-class"><span class="hljs-keyword">extension</span> <span class="hljs-title">Order</span> </span>{
    <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fixture</span><span class="hljs-params">(
        uuid: String = <span class="hljs-string">""</span>, 
        date: Date = Date<span class="hljs-params">(timeIntervalSince1970: <span class="hljs-number">0</span>)</span></span></span>, 
        items: [<span class="hljs-type">Item</span>] = [], 
        totalPrice: <span class="hljs-type">Decimal</span> = <span class="hljs-number">0.0</span>, 
        discount: <span class="hljs-type">Decimal</span> = <span class="hljs-number">0.0</span>, 
        seller: <span class="hljs-type">Seller</span> = .fixture()
    ) -&gt; <span class="hljs-type">Order</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-type">Order</span>(
            uuid: uuid,
            date: date, 
            items: items, 
            totalPrice: totalPrice, 
            discount: discount, 
            seller: seller
        )
    }
}

<span class="hljs-class"><span class="hljs-keyword">extension</span> <span class="hljs-title">Seller</span> </span>{
    <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fixture</span><span class="hljs-params">(
        uuid: String = <span class="hljs-string">""</span>,
        name: String = <span class="hljs-string">""</span>,
        websiteUrl: URL = .fixture<span class="hljs-params">()</span></span></span>
    ) -&gt; <span class="hljs-type">Seller</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-type">Seller</span>(
            uuid: uuid,
            name: name,
            websiteUrl: websiteUrl
        )
    }
}

<span class="hljs-class"><span class="hljs-keyword">extension</span> <span class="hljs-title">URL</span> </span>{
    <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fixture</span><span class="hljs-params">(string: String = <span class="hljs-string">""</span>)</span></span> -&gt; <span class="hljs-type">URL</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-type">URL</span>(fileURLWithPath: string)
    }
}
</code></pre>
<p>Simple as that, but we need to consider some things in my implementation:</p>
<ol>
<li>Note that I created a new fixture recursively for each dependency. It's up to you. Create fixtures as you go and feel that it's needed</li>
<li>I created every fixture in a single file by convenience. You can separate them into different files if you want. No problem.</li>
<li>Double attention to the default values. Aways prefer using empties, zeroes and non-failable values on fixtures default values. Otherwise, we can be lead to flakiness, especially when working with <code>Date</code>.</li>
<li>Why not a <code>convenience init</code>? Using a convenience init wouldn't work because you will be creating a new init with the same argument labels that you defined on the production code, and the compiler will complain about it. On the other hand, using the <code>fixture</code> term tells the reader the code is getting a test value more explicitly.</li>
</ol>
<h1 id="heading-conclusion">Conclusion</h1>
<p>This was a short tip on how you can make your tests cleaner by arranging the test cases with Fixtures. 
The way I implemented is a humble suggestion to inspire you. Put it in practice. I strongly believe that it will bring you awesome results.
There are a bunch of more techniques to write better tests I will explore with you during this year, so stay tuned. See ya!</p>
<hr />
<p><strong>References:</strong></p>
<ul>
<li><a target="_blank" href="https://mokacoding.com/blog/streamlining-tests-setup-with-fixtures-in-swift/">Streamlining tests setup with fixtures in SwiftUntitled</a></li>
<li><a target="_blank" href="https://medium.com/@bruno.hcr/swift-tests-tips-tricks-fixture-object-pattern-5decefe6f10c">Swift Tests Tips &amp; Tricks: Fixture Object Pattern</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[What should I test?]]></title><description><![CDATA[I got stuck when writing unit tests
When I started writing unit tests, I faced a problem that you are most likely facing now. I've watched some unit test tutorials, but I got stuck and didn't know what to test when I put it into practice.
Should I te...]]></description><link>https://policiano.com/2022-01-22-what-should-i-test</link><guid isPermaLink="true">https://policiano.com/2022-01-22-what-should-i-test</guid><category><![CDATA[Testing]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[solid]]></category><category><![CDATA[unit testing]]></category><category><![CDATA[Swift]]></category><dc:creator><![CDATA[Will Policiano]]></dc:creator><pubDate>Sat, 22 Jan 2022 18:04:14 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-i-got-stuck-when-writing-unit-tests">I got stuck when writing unit tests</h1>
<p>When I started writing unit tests, I faced a problem that you are most likely facing now. I've watched some unit test tutorials, but I got stuck and didn't know what to test when I put it into practice.</p>
<p>Should I test everything? Only the domain components? Should I test the CocoaPods I've been using? Should I test every single branch statement in my code? That feeling is terrible and almost made me give up.</p>
<p>After answering these questions, I caught myself in another tricky situation. My tests became too hard to maintain. But what was I doing wrong?</p>
<h1 id="heading-key-tips-to-know-what-to-test">Key tips to know what to test</h1>
<p>I didn't know what to test, and to solve that, I followed some simple tips. Check it out!</p>
<h2 id="heading-1-follow-design-principles">1. Follow design principles</h2>
<p>As hard your test cases are, as badly designed your code is. This means that if your test is becoming hard to maintain, you have code smells in the subject under the test. </p>
<p>See some <strong>red flags warning you that your code should be redesigned</strong>. </p>
<ul>
<li>Massive test setup and teardown</li>
<li>Big test methods</li>
<li>Big test case classes</li>
<li>Flaky tests</li>
</ul>
<p>In this case, we need to check our code and refactor it due to applying some design principles. I recommend you study more about <strong>Design Patterns, Software Design Principles, and SOLID.</strong> However, to save your time, I strongly recommend you to explore the <strong>Dependency Injection</strong> and after <strong>Dependency Inversion Principle.</strong></p>
<p>Dependency Inversion is the key to testability. When you apply it in your project, your code becomes more testable and enables us to use <strong>Test Doubles</strong> to pretend some system behaviors to achieve the real pure unit test.</p>
<p>The other design patterns also will be conducive, but you had better master the Dependency Injection and Inversion as soon as possible.</p>
<h2 id="heading-2-test-over-the-public-api">2. Test over the public API</h2>
<p>A good practice that we follow is to control the class access through the <code>private</code>, <code>internal</code>, <code>public</code> modifiers. And this makes our test hard at a glance.</p>
<p>We should test our classes from the point of view of its consumers. Therefore, we need to test over the class’ public API.</p>
<p>We don't need to let all the class property and method public in favor of testability. This will bring us some design problems and some unexpected behavior. After all, we need to protect ourselves from ourselves. So, focus on testing the public API, which the class consumers actually use.</p>
<p>But what about my private API?</p>
<p>We will eventually test them implicitly by testing the public API. We need to configure the appropriate inputs to execute the private methods. When some private API becomes too hard to execute, it may indicate that your class has too much responsibility. It's time to refactor.</p>
<h2 id="heading-3-test-the-behavior-not-the-structure">3. Test the behavior, not the structure</h2>
<p>As beginners, we tend to look for each <code>if-else</code>, <code>switch</code>, <code>guard</code>, and design all tests to cover these branches. Well, that's a good strategy, but it's not my favorite.</p>
<p>Testing by looking at code structure leaves our test cases referring to code structure. As a result, always when our code suffers refactoring, the test will also have to be refactored. Our tests become rigid and hard to maintain.</p>
<p>I prefer to test the app's behavior, the use-cases, the features. In this case, <strong>the tests will only need to be changed if the behavior of the app changes</strong>. Otherwise, we can freely refactor our code, and the tests will continue to work. That's one of the main benefits of the unit tests: <strong>Make the software soft and easy to change.</strong></p>
<p>Testing the behavior also implies that we won't need a test class for every single production class in our app, because we can implicitly test, through integration, more than one class.</p>
<h2 id="heading-4-dont-test-third-party-code">4. Don't test third party code</h2>
<p>Finally, I would say that we don't need to test third-party code. I always assume it is already tested. For example, I don't need to write tests to make sure Decodable works because I assume Apple has already done that. Same idea for an open-source code like Alamofire. It's not a rule if you feel safer writing tests for third-party code, no problem! In general, we can assume that third parties have already tested these codes.</p>
<h1 id="heading-bonus">Bonus</h1>
<p>If after all these tips you are still feeling stuck, don't worry, step back and see this advices:</p>
<h2 id="heading-test-your-code-first">Test your code first</h2>
<p>Testing code you haven't written can be tricky. It will become progressively easier:</p>
<ol>
<li>I strongly suggest that you start by testing new classes that you are creating. It is much easier to add tests to something that is being created from scratch.</li>
<li>The next step is to add tests to the code you wrote a while ago.</li>
<li>Then write tests for bug fixes.</li>
<li>Here you start to have contact with code that is not yours.</li>
<li>Finally, you will be adding tests to the code you are working on, whether you wrote it or not.</li>
</ol>
<p>I did it this way and I highly recommend it. It is much easier to first learn how to test in our code. Once we've learned, it's just a matter of moving on to other people's codes.</p>
<h2 id="heading-lack-of-requirement-analysis">Lack of Requirement Analysis</h2>
<p>Sometimes we got stuck because we don't fully understand the feature we are implementing. Step back and write down all the requirements for that feature. Do it with the Product Manager, Team Manager, Designer, and your pairs. It's part of the project planning and I don't recommend writing any line of code before you fully understand the feature. </p>
<p>Collect the happy path and all the possible error courses that the feature can run. After all, start implementing the feature.</p>
<h2 id="heading-routine">Routine</h2>
<p>Mastering unit testing demands practice and consistency. Don't be overly depressed about it, even if it is hard for you. Just keep trying, slowly, step-by-step, every day, and unit testing will become as natural as breathing for you.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>To wrap it up, it's normal to get stuck when writing unit tests. It doesn't mean we don't know how to write unit tests but indicates that we need more attention on what to test. </p>
<p>This is my second article and I hope it helps you. Next posts <strong>I will start writing some Swift testing tips</strong>. Stay tuned! See ya!</p>
]]></content:encoded></item><item><title><![CDATA[Start Unit Testing right now]]></title><description><![CDATA[Most likely, you've heard about unit testing and know what it is. I found unit tests out in 2011, but I actually used them just in 2018.
Writing unit tests has brought many benefits, both for the apps I develop and my career, but why did it take me s...]]></description><link>https://policiano.com/2022-01-14start-unit-testing-right-now</link><guid isPermaLink="true">https://policiano.com/2022-01-14start-unit-testing-right-now</guid><category><![CDATA[Testing]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[leadership]]></category><category><![CDATA[Career]]></category><category><![CDATA[Swift]]></category><dc:creator><![CDATA[Will Policiano]]></dc:creator><pubDate>Fri, 14 Jan 2022 22:53:21 GMT</pubDate><content:encoded><![CDATA[<p>Most likely, you've heard about unit testing and know what it is. I found unit tests out in 2011, but I actually used them just in 2018.</p>
<p>Writing unit tests has brought many benefits, both for the apps I develop and my career, but why did it take me so long to put this into practice?</p>
<p>In this post, I will present the barriers that developers often face that make them delay or even give up on the idea of writing unit tests.</p>
<p>So follow the tips until the end. I'm sure you'll want to write your first unit test today.</p>
<h1 id="heading-what-is-a-unit-test">What is a Unit Test?</h1>
<p>Unit Tests are low-level automated tests that focus on ensuring the correct functionality of small parts of the system. We can call these pieces <strong>unit</strong>, hence the name Unit Test. Test the unit, not the whole.</p>
<p>What we might disagree about is what is really a unit is. A unit can be anything from a function/method to a complete module. This definition will vary according to the context of the system, the developers, the team, and so on. However, I have noticed a consensus among iOS developers, who consider <strong>the public methods</strong> as a unit.</p>
<p>To understand better, let's take a look at the famous pyramid of test types:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1642200269108/Lcy5IP60_.png" alt="Pyramid.png" /></p>
<p>This pyramid is divided into three types of tests. I can detail each type better in a future post, but the thing is that unit tests should be in greater volume in our project, as they are more isolated (and therefore easier to implement) and are very fast since we need to run them hundreds of times a day.</p>
<p>Therefore, we may agree that unit tests are the least expensive and bring the most benefits. Let's see why.</p>
<h1 id="heading-why-should-i-write-automated-tests">Why should I write automated tests?</h1>
<p>I have asked myself this question several times. "I'm a developer, and QA is not my responsibility", I said.</p>
<p>We might not be responsible for the quality or the product's success, but I firmly believe that we are accountable for the quality of our work.</p>
<p>So as a professional developer, yes, I am responsible for ensuring the quality of the code I write. Besides, it's not just about professionalism. It's also about having a peaceful night's sleep, confidence in our excellent work and keeping yourself motivated.</p>
<p>There are numerous benefits to writing unit tests. Let's start with the programmer's benefits:</p>
<ul>
<li><strong>Get proud of your work</strong>: You will be able to finish the workday peacefully, as it is unlikely that your code has bugs.</li>
<li><strong>Confidence when leading with legacy code:</strong> Change legacy code freely without being afraid of breaking something because if you do, the tests will let you know before you ship the app.</li>
<li><strong>Refactoring:</strong> Code that has tests is future-ready. We can freely refactor using new technologies because the tests will ensure that the app's behaviour will keep working as expected.</li>
<li><strong>Auto-Documentation:</strong> When we write tests, we are also documenting, which increases our requirements analysis skills. It's incredible how we discover several gaps in the app's functionality when writing the tests.</li>
<li><strong>Avoid bug regression:</strong> Say goodbye to "I thought that I already fixed that".</li>
<li><strong>Faster test suites:</strong> Decreases the need to run UI tests, which are much more expensive.</li>
</ul>
<p>Your manager/client/company gets beneficiated as well. The main thing is the possibility of implementing a CI (Continuous Integration) and CD (Continuous Delivery), which enables all the following benefits:</p>
<ul>
<li><strong>Continuous Delivery:</strong> As the code is always stable and tested, the manager doesn't have to wait weeks or months to release an app version. Much more confidence when shipping their apps.</li>
<li><strong>Continuous feature feedback:</strong> The consumer can build from the last main branch commit and try it on. They can do this several times a day and send you feedbacks/bug reports frequently.</li>
<li><strong>Lower incidence of bugs:</strong> Bugs can be caught earlier during the development and can be fixed real quick.</li>
<li><strong>Lower cost in general:</strong> A good quality project doesn't require a developer army. The manager won't need many QA people, and they won't need to spend much of their own time testing the app either. Also, fewer bugs mean satisfied users.</li>
<li><strong>Trust in the relationship of developers and stakeholders:</strong> The team gets more motivated and honest. There's nothing worse than a dissatisfied manager with an app full of bugs and frustrated developers in the same team.</li>
</ul>
<p>Note that this is not just about good code. Writing unit tests expands the company's matter.</p>
<h1 id="heading-i-dont-have-time">I don't have time</h1>
<p>I was working in a software house when I started studying unit testing. There, estimates and deadlines are sacred. Also, as a beginner developer and didn't have a flair for negotiating extra time to add unit tests to the project.</p>
<p>The point is: Do not negotiate. Just do it.</p>
<p>Once I understood this, I started writing my tests.</p>
<p>Your boss and your client don't care if the product has unit tests or not. They want to see the app working promptly. If you ask them to choose between Speed and Quality, they will undoubtedly select both. However, we know there is no way to conciliate speed and quality. We need to balance them. It's tricky because quality brings speed in the mid-long term.</p>
<p>We don't negotiate because they don't understand, and they actually don't need to. The developer is you. They choose <strong>what to do</strong>, and you decide <strong>how to do it.</strong> You are the specialist.</p>
<p>Of course, we can't just blow our estimates up without a good reason. If you're a beginner like I was, start slowly. Allocate an hour or two per week to writing tests. Don't worry about covering everything. With practice, writing tests becomes natural, and you will write tests faster and faster.</p>
<p>Once you've kicked things off, it's also essential that you gather the results of having written the tests and present them to stakeholders. So they may look with a different perspective and start to institutionalize this practice in the company.</p>
<p>Simple. Just get started without necessarily asking for permission. This risk is worth it if you want to become a first-class developer.</p>
<h1 id="heading-code-coverage-obsession">Code coverage obsession</h1>
<p>Once we start writing unit tests, we will become obsessed with the famous Code Coverage. Code coverage is a good metric to understand how much tested code we have in the project.</p>
<p>Basically, it's a percentage of code lines executed during unit tests.</p>
<p>At first, we were obsessed with increasing this number, as it is one of the few quality metrics related to unit tests. This obsession becomes frustrating to us, especially in big projects. As big as the project is as hard to increase the coverage, and we will often see this number decreasing.</p>
<p>Note that this percentage doesn't prove much. Executing a given piece of code does not guarantee that it behaves correctly. Do you agree?</p>
<p>Finally, always try to cover all the use cases/behaviour of the project and the ~100% coverage will come as a reward for it.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>In this post, I wanted to briefly introduce unit tests and share my experiences to convince you to write tests as soon as possible. For this post not to get too long, I decided to leave the hands-on for another post.</p>
<p>I hope this article has been helpful for you, and if you want to delve deeper into this topic, I'll be making regular posts on more advanced testing topics. If you want to learn how to write unit tests, check out this <a target="_blank" href="https://www.raywenderlich.com/21020457-ios-unit-testing-and-ui-testing-tutorial">excellent article</a>. See you!</p>
]]></content:encoded></item></channel></rss>