<?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 Asilbek Djamaldinov on Medium]]></title>
        <description><![CDATA[Stories by Asilbek Djamaldinov on Medium]]></description>
        <link>https://medium.com/@asilbekdjamaldinov?source=rss-db3fa83d07d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CxP5ZjAhlO75BZxasSwNcw.jpeg</url>
            <title>Stories by Asilbek Djamaldinov on Medium</title>
            <link>https://medium.com/@asilbekdjamaldinov?source=rss-db3fa83d07d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 09:25:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asilbekdjamaldinov/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[Performance tests in iOS]]></title>
            <link>https://medium.com/@asilbekdjamaldinov/performance-tests-in-ios-fcf2ba40caf4?source=rss-db3fa83d07d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcf2ba40caf4</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Asilbek Djamaldinov]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 00:17:56 GMT</pubDate>
            <atom:updated>2024-01-22T00:17:56.222Z</atom:updated>
            <content:encoded><![CDATA[<p>We won’t delve into the fundamentals of iOS testing here. If you need a refresher on how to write unit tests, you can check out my <a href="https://medium.com/@asilbekdjamaldinov/testing-in-ios-from-zero-to-hero-b097d1819fa6">earlier article</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UpmN9rYbNOT-NuLXHTZbHg.jpeg" /></figure><h4>What do performance tests in iOS mean, and why are they important?</h4><p>Performance tests in iOS are like doctor check-ups for the important tasks your device does. They make sure these tasks run as fast as they’re supposed to. If something’s not right (like failing a check-up), the system will tell you about it.</p><p>These tests help find out if your apps are opening fast, if the device responds quickly to your touches, and if it doesn’t get too slow or hot when you use it for a long time.</p><h4>Let’s write some code</h4><p>The XCTest library gives us a handy measure(_:) function to check how fast things are happening. First, let&#39;s explore the basic version without any extra settings.</p><p>We are going to examine this function.</p><pre>class ViewModel {<br>    var count = 0<br>    <br>    func heavyCalculation() {<br>        for i in 0..&lt;1_000_000 {<br>            count += 1<br>        }<br>    }<br>}</pre><p>Nothing too fancy going on here, so let’s write a test case for it right away.</p><pre>final class ViewModelTests: XCTestCase {<br>  // Standard testing code setUp() and tearDown() <br>  ...<br><br>  func test_viewModel_heavyCalculation_isPerformanceSatisfing() {<br>        measure {<br>            sut.heavyCalculation()<br>        }<br>    }<br>}</pre><p>When we run this test, the final result will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s26oCIwCaVvnkGYA6h7xgQ.png" /></figure><p>You might be wondering, “What does that mean?” It means we didn’t tell the system what time is considered good or bad for this test. Is it okay that the function finished in 0.949 seconds, or is that too slow? We need to give the system some guidelines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0fIlMqYsFJCSRJYeZBSkyw.png" /></figure><p>We need to establish a baseline, and I believe that 1 second is a reasonable time for this function to pass our test. Let’s go ahead and set that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*03Pt7-J-BXPG4tynOH3E8A.png" /></figure><p>Let me break down the result variables for you. The “metric” is time because we’re checking how long the function takes to finish, which makes sense. The “average” is the middle value from 10 runs of the function, giving us an overall average. The “baseline” is what we set as our expected standard. The “max STDDEV” (standard deviation) is the acceptable difference for our test. By default, it’s 10%, but we can adjust it to fit our specific requirements.</p><p>Give the test another go and check the results a few times. Usually, they won’t vary much from what we got the first time.</p><p>Now, let’s switch things up and change the function from 1 million to 2 million.</p><pre>func heavyCalculation() {<br>    for i in 0..&lt;2_000_000 {<br>        count += 1<br>    }<br>}</pre><p>After making the change, let’s run the test again and see how the results look this time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AlqBLCYA99GhHf6Yj934gw.png" /></figure><p>Indeed, the test failed because our method couldn’t stay within the range we set (0.9–1.1 seconds). This suggests that our method has slowed down.</p><p>Certainly, we can reconsider our boundaries, but it’s crucial to align them with the business requirements. Adjusting the criteria should reflect what’s acceptable and meaningful for the overall functionality of our application.</p><h4>measure(metrics:options:block:)</h4><p>Let’s explore other examples using the extended function <strong>measure(metrics:options:block:)</strong>. This function allows us to gather more detailed metrics and options during the performance evaluation.</p><ul><li><strong>Metrics:</strong> This parameter allows us to specify the performance metrics we want to measure. For example, we can track things like the time it takes, the amount of memory used, or other relevant metrics.</li><li><strong>Options:</strong> This parameter lets us set various options for the performance measurement, like whether to run the block asynchronously or repeatedly.</li></ul><pre>func test_viewModel_heavyCalculation_isPerformanceSatisfing() {<br>    let metrics: [XCTMetric] = [XCTMemoryMetric(), XCTClockMetric(), XCTCPUMetric()]<br>    let measureOptions = XCTMeasureOptions.default<br>    measureOptions.iterationCount = 5<br>    <br>    measure(metrics: metrics, options: measureOptions) {<br>        sut.heavyCalculation()<br>    }<br>}</pre><p>Let’s break down the key components:</p><ol><li><strong>Metrics Array:</strong> We’ve defined an array called <strong>metrics</strong> that includes three performance metrics: <strong>XCTMemoryMetric()</strong> (measuring memory usage), <strong>XCTClockMetric()</strong> (measuring time), and <strong>XCTCPUMetric()</strong>(measuring CPU usage).</li><li><strong>Measure Options:</strong> We’ve created an instance of <strong>XCTMeasureOptions</strong> called <strong>measureOptions</strong> with the default settings. Additionally, we&#39;ve set the <strong>iterationCount</strong> to 5. This means the **heavyCalculation** will be performed five times, and metrics will be collected for each iteration.</li></ol><h4>Conclusion</h4><p>In summary, performance tests are a crucial aspect of iOS development, ensuring that apps run smoothly and meet the expected performance criteria. Regular evaluations help maintain a healthy and responsive user experience.</p><h4>Find it a good read?</h4><p>Recommend this post by clicking the 👏 button so other people can see it and let’s connect on LinkedIn <a href="https://www.linkedin.com/in/asilbekdjamaldinov/"><strong>asilbekdjamaldinov</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcf2ba40caf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test Driven Development (TDD) in iOS]]></title>
            <link>https://medium.com/@asilbekdjamaldinov/test-driven-development-tdd-in-ios-24e96ff310f8?source=rss-db3fa83d07d------2</link>
            <guid isPermaLink="false">https://medium.com/p/24e96ff310f8</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Asilbek Djamaldinov]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 01:42:05 GMT</pubDate>
            <atom:updated>2024-01-21T01:42:05.899Z</atom:updated>
            <content:encoded><![CDATA[<p>We won’t delve into the fundamentals of iOS testing here. If you need a refresher on how to write unit tests, you can check out my <a href="https://medium.com/@asilbekdjamaldinov/testing-in-ios-from-zero-to-hero-b097d1819fa6">earlier article</a>.</p><h4>Understanding TDD</h4><p>At this point, it’s widely understood that TDD instructs us to create unit tests before developing production code — a fundamental principle. However, this principle is just the beginning. Let’s explore the three foundational laws:</p><ol><li><strong>First Law:</strong> It is prohibited to create production code without first generating a failing unit test.</li><li><strong>Second Law:</strong> The creation of a unit test should only cover what is necessary for it to fail, and failure includes not compiling.</li><li><strong>Third Law:</strong> The development of production code should only address the requirements needed to pass the current failing test.</li></ol><p>TDD promotes a more robust and reliable codebase by enforcing a systematic and iterative process of writing tests and code. It helps catch defects early, encourages modular and maintainable code, and provides a safety net for future changes.</p><blockquote><em>Make sure you focus on “encourages modular and maintainable code”. In simple terms, TDD makes us write code in small, manageable parts, ensuring it’s easy to maintain.</em></blockquote><p>TDD operates on a simple, yet powerful cycle: write a test, make it fail, write the code to make the test pass, and then refactor the code while keeping all tests passing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3TPIg9vHBKFHXmmsrMz0Rg.png" /><figcaption><a href="http://marsner.com/">Source: marsner.com</a></figcaption></figure><h4>Key Principles of TDD in iOS:</h4><ol><li><strong>Red-Green-Refactor Cycle:</strong> The foundation of TDD lies in the Red-Green-Refactor cycle. Developers start by writing a failing test (Red), then implement the minimum code necessary to make the test pass (Green), and finally refactor the code to improve its structure and maintainability.</li><li><strong>Write Minimal Code:</strong> TDD encourages developers to write the minimum amount of code required to pass the test. This ensures that the codebase remains concise and focused on meeting specific requirements.</li><li><strong>Continuous Integration:</strong> Automated testing is a crucial aspect of TDD. Integrating continuous integration tools helps run tests automatically whenever changes are made to the codebase, providing immediate feedback and preventing the introduction of bugs.</li></ol><h4>Let’s code</h4><p>We’re starting to test the CalculatorViewModelTests, and here’s how our code looks initially.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LSi6mEWKVlnmunNO3OgrTQ.png" /></figure><p>There is nothing new yet. Sure, let’s add a test case for a new function that we haven’t implemented yet in the CalculatorViewModelTests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqG9PbUvn1wTRD9sh08xfg.png" /></figure><p>Right! When it comes to making changes or adding new features, we follow the rule of writing a test first before making any changes to the actual code, even for creating files and classes. This way, we’ve successfully followed the first and the second rules — we’ve not added a new production code yet and created a test case that currently fails. Project is not compiling, which means that test failed.</p><p>We’ll create a class named CalculatorViewModel, and now we’re following the third rule — we’ll add code that specifically meets the requirements to make the tests pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRaGpjG3roHpTpHt_x6_Uw.png" /></figure><p>Alright, let’s create a function for adding two variables, but remember, we need to begin by writing a test case for it first. After that, we can proceed to write the actual code. Remember, test first, then production code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8S90A2ds2E0NaTHd7_hcVQ.png" /></figure><p>Here we go again. The code isn’t compiling, and that’s exactly what we want. It’s intentional — we write tests that are meant to fail. Afterward, we fix the production code to make the tests pass. This ensures that we’re writing code with a clear understanding of the expected output.</p><p>Now let’s fix it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suIMgVCx7Wuk8xT028eQtw.png" /></figure><p>Easy, isn’t it? Now, let’s add another method for subtraction. Just a friendly reminder — we start with the test, and only after that, we write the production code. Keep the order in mind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TH9RhwLRJL4Eci3n279PDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tbtl2gMygGp8rUCL49NSzA.png" /></figure><p>Fantastic progress! We’re almost done, but there’s one more crucial step we haven’t addressed — refactoring. Take a look at the TDD diagram: (1) write a failing test, (2) make the test pass, and (3) refactor. Let’s explore what improvements we can make during the refactoring phase.</p><p>The only adjustment we can consider is making ‘a’ and ‘b’ variables class variables. This will result in slightly smaller test cases and having two class variables.</p><p>Remember, it’s crucial to refactor both your test and production code. Clean and readable code is essential not only for the production side but also for the test side. Refactoring is a vital stage after each test — never overlook it. If you were to prioritize the three stages, I would emphasize that refactoring is the most important.</p><blockquote><em>Test code should be just as clean and readable as your production code.</em></blockquote><h4>Conclusion</h4><p>In conclusion, an increasing number of companies include TDD as a requirement in their job descriptions. This is because TDD not only aids in safeguarding the codebase against various bugs but also contributes to the development of a robust and well-architected codebase.</p><h4>Find it a good read?</h4><p>Recommend this post by clicking the 👏 button so other people can see it and let’s connect on LinkedIn <a href="https://www.linkedin.com/in/asilbekdjamaldinov/"><strong>asilbekdjamaldinov</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24e96ff310f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why to Unit Test in Async Mode]]></title>
            <link>https://medium.com/@asilbekdjamaldinov/why-to-unit-test-in-async-mode-b9efec1c20ef?source=rss-db3fa83d07d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9efec1c20ef</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[asyncawait]]></category>
            <dc:creator><![CDATA[Asilbek Djamaldinov]]></dc:creator>
            <pubDate>Sat, 28 Oct 2023 23:23:03 GMT</pubDate>
            <atom:updated>2023-10-29T12:23:58.930Z</atom:updated>
            <content:encoded><![CDATA[<p>Here are my other articles of the Testing Flow in iOS :</p><ol><li><a href="https://medium.com/p/b097d1819fa6">Testing in iOS: From Zero to Hero!</a></li><li><a href="https://medium.com/p/ba1b34f1d09e#994c-18d6620e7f4d">Unlocking the Power of UI Testing in iOS Development</a></li><li><a href="https://medium.com/@asilbekdjamaldinov/why-mocking-matters-in-ios-unit-testing-9c6ee4a7241b">Why Mocking Matters in iOS Unit Testing</a></li><li><a href="https://medium.com/@asilbekdjamaldinov/ios-dev-must-have-snapshot-testing-0cc78d9b7ef9">iOS Dev Must-Have: Snapshot Testing</a></li><li>Why to Unit Test in Async Mode (current)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Bhsd_R0tdj2lF09CBszGA.jpeg" /></figure><p>Welcome to the fifth and final chapter in our joyful journey through the intricate world of iOS testing. By now, you’ve likely mastered the art of unit testing and gained insights into a variety of testing techniques, but there’s one more crucial skill to add to your arsenal: unit testing in asynchronous environments.</p><p>In this article, we’re going to delve into the exciting realm of asynchronous unit testing, equipping you with the knowledge and skills necessary to ensure your iOS applications are robust, reliable, and free from pesky bugs. While we can’t cover every nook and cranny of testing in a single article, this guide will serve as a springboard for you to confidently venture into the world of testing in the iOS ecosystem.</p><p>So, whether you’re a seasoned iOS developer looking to enhance your testing abilities or a newcomer keen to get started, fasten your seatbelts. We’re about to embark on a delightful journey that will make you an expert in iOS testing, enabling you to create apps that stand the test of time. Get ready to write unit tests in asynchronous environments with joy and confidence!</p><h3>Why we need asynchronous testing?</h3><p>In iOS, we often work with asynchronous operations and multiple threads, even if it’s not immediately visible. While we’re aware that network tasks are asynchronous, there are times when we might not notice that specific pieces of code are running in the background or are designed to work asynchronously.</p><p>A big chunk of our iOS code is closely tied to asynchronous stuff: like networking, event listeners, closures, handling notifications, working with Combine publishers, and even user interactions. And there’s more — these asynchronous elements are woven into the fabric of our apps, making them dynamic and responsive.</p><p>Testing in an asynchronous iOS environment can be a tad trickier than in a synchronous one. However, don’t fret; it’s not a daunting task. Thanks to Apple, we’ve got a bunch of nifty tools at our disposal to craft tests and manage how our code behaves with ease. So, while it’s a bit different, it’s far from difficult, and these tools are here to make your testing journey a smooth one.</p><p>Alright, enough with the words — let’s sketch out a strategy to conquer the beast called “asynchronous testing.” We’re going to map out a plan to tackle it head-on, making sure it doesn’t stand in the way of our app’s success.</p><h3>Our Topics For Today</h3><ol><li>Mocking: Surprisingly Problem-Solving</li><li>What to Expect From XCTestExpectation</li><li>Fulfilment Will Help You More Than You Think</li><li>New Testing Strategy for New Way of Concurrency</li></ol><h4>Topic 1: How to Achieve Synchronous Code with Mocking</h4><p>The best way to tackle a problem is not having one in the first place, right? Honestly, the most elegant solution is simply getting rid of the problem itself. So, when we’re testing our asynchronous code, our first move is to attempt to kick out the asynchronous part. Of course, it doesn’t always work, but hey, we’ve got to give it a shot!</p><p>Let’s imagine we’ve got this service that likes to chat with the cloud asynchronously:</p><pre>protocol AnyService {<br>    var value: Int { get }<br>    <br>    func someAsyncOperation() <br>}<br><br>class CloudService: AnyService {<br>    var value: Int = 0<br>    <br>    func someAsyncOperation() {<br>        DispatchQueue.global().asyncAfter(deadline: .now() + 3) { [weak self] in<br>            self?.value = 1<br>        }<br>    }<br>}</pre><p>Now, picture our trusty viewModel, which, inside one of its functions, gives our service a ring. Just a quick heads-up, this article won’t dive deep into the nitty-gritty of mocking. But if you’re curious, there’s <a href="https://medium.com/@asilbekdjamaldinov/why-mocking-matters-in-ios-unit-testing-9c6ee4a7241b">another article</a> where we unravel the mysteries of mocking — so feel free to check that out if you’ve got questions!</p><pre>class DeepOceanViewModel {<br>    let service: AnyService<br>    <br>    init(service: AnyService = CloudService()) {<br>        self.service = service<br>    }<br>    <br>    func callSomeAsyncOperation() {<br>        service.someAsyncOperation()<br>    }<br>}</pre><p>Time to craft a test for this setup!</p><pre>// Without mocking<br>final class MyOceanTestsTests: XCTestCase {<br>    ...<br>    <br>    func test_DeepOceanViewModel_callSomeAsyncOperation_didIncreaseValue() {<br>        // when<br>        sut.callSomeAsyncOperation()<br>        <br>        // then<br>        XCTAssertEqual(sut.service.value, 1)<br>    }<br>}</pre><p>Do you think this test will succeed? Nope, it won’t. The test will wrap up before the value gets a chance to increase.</p><p>Let’s implement mocking for this test case:</p><pre>class MockCloudService: AnyService {<br>    var value: Int = 0<br>    <br>    func someAsyncOperation() {<br>        value = 1<br>    }<br>}</pre><p>Let’s take a closer look at our handy <strong>MockCloudService</strong> class. In the <strong>someAsyncOperation</strong> function, we&#39;ve done a little trick. Instead of the usual asynchronous stuff, it now works like regular, straightforward code – no waiting around. That&#39;s the magic of mocking that makes our asynchronous tests a piece of testable cake!</p><pre>final class MyOceanTestsTests: XCTestCase {<br>    var sut: DeepOceanViewModel!<br>    var mockCloudService: MockCloudService!<br>    <br>    override func setUp() {<br>        super.setUp()<br>        mockCloudService = MockCloudService()<br>        sut = DeepOceanViewModel(service: mockCloudService)<br>    }<br>    <br>    ...<br>    <br>    func test_DeepOceanViewModel_callSomeAsyncOperation_didIncreaseValue() {<br>        // when<br>        sut.callSomeAsyncOperation()<br>        <br>        // then<br>        XCTAssertEqual(sut.service.value, 1)<br>    }<br>}</pre><p>Let’s fire it up and take a peek… Yippee! It passes with flying colours. That’s the sheer strength of mocking, making our testing journey smooth as butter!</p><h4>Topic 2: Our Expectations from XCTestExpectation</h4><p><strong>XCTestExpectation</strong> is a part of Apple&#39;s XCTest framework and a very powerful tool for asynchronous testing. It allows us to wait for specific conditions or events to occur in the code during testing.</p><p>Here’s a simple 3-step guide to using <strong>XCTestExpectation</strong>:</p><ol><li>Create your expectation.</li><li>Pause and wait for it to be met.</li><li>Make it happen — fulfill the expectation when your condition is satisfied.</li></ol><p>It’s as straightforward as that! Truth be told, testing isn’t all that tricky, especially when you develop it hand-in-hand with well-organised code. It’s a recipe for success!</p><p>In this testing method, we’ll be testing another asynchronous function with closure.</p><pre>class DeepOceanViewModel {<br>    var value: Int = 0<br>    ...<br>    <br>    func anotherAsyncOperation(completion: @escaping () -&gt; ()) {<br>        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {<br>            value = 77<br>            completion()<br>        }<br>    }<br>}</pre><p>Mocking isn’t a one-size-fits-all solution for asynchronous testing. That’s why we enlist the help of XCTestExpectation. It’s crucial to note that XCTestExpectation isn’t meant to replace mocking; instead, it complements it. In most cases, you’ll use mocking for service calls and XCTestExpectation to handle test cases with asynchronous expectations. They’re a dynamic duo in the world of testing!</p><pre>final class MyOceanTestsTests: XCTestCase {<br>    ...<br><br>    func test_DeepOceanViewModel_anotherAsyncOperation_didCallCompletion() {<br>        // given<br>        let expectation = XCTestExpectation(description: #function)<br>        <br>        // when<br>        sut.anotherAsyncOperation {<br>            expectation.fulfill()<br>        }<br>        <br>        waitForExpectations(timeout: 3)<br>        <br>        // then<br>        XCTAssertEqual(sut.value, 77)<br>    }<br>}</pre><p>In this test:</p><ul><li><strong>Given</strong>: We prepare for an asynchronous operation by creating an expectation with the test case’s name.</li><li><strong>When</strong>: We initiate the asynchronous operation and set a 3-second maximum waiting time. If the operation completes earlier due to <strong>expectation.fulfill()</strong>, the test proceeds to make an assertion.</li><li><strong>Then</strong>: We verify whether <strong>sut.value</strong> is equal to 77.</li></ul><p>If everything goes as planned, the test passes; if not, it fails, indicating potential code issues.</p><h4>Topic 3: How to fulfil that’s already been filled?</h4><p>In app development, we frequently employ a debouncer to manage button clicks or search logic, preventing multiple server calls. Let’s now craft a unit test for this kind of function. Debouncer code you can find <a href="https://betterprogramming.pub/implement-a-debouncer-in-swift-3b5c775f90b8">here</a>.</p><pre>class DeepOceanViewModel {<br>  let debouncer = Debouncer(timeInterval: 0.3)<br><br>  ...<br>    <br>  func searchWithDebouncer(_ value: String, completion: @escaping () -&gt; ()) {<br>      debouncer.renewInterval()<br>        <br>      debouncer.handler = {<br>          service.search(for: value)<br>      completion()<br>      }<br>  }<br>}</pre><p>In this scenario, we’re going to perform two very quick calls to the search method. We’ll wait for only one expectation to occur. If both expectations are fulfilled, it indicates a test failure. To fail the test when an expectation is met, we’ll set <strong>cancelExpectation.isInverted</strong> to <strong>true</strong>.</p><pre>func test_DeepOceanViewModel_searchWithDebouncer_oneExpectationFulfilled() {<br>    // given<br>    let canceledExpectation = XCTestExpectation(description: &quot;Canceled&quot;)<br>    canceledExpectation.isInverted = true<br>        <br>    let completedExpectation = XCTestExpectation(description: &quot;Completed&quot;)<br>        <br>    // when<br>    sut.searchWithDebouncer(&quot;Cancel&quot;) {<br>        canceledExpectation.fulfill()<br>    }<br>        <br>    sut.searchWithDebouncer(&quot;Completed&quot;) {<br>        completedExpectation.fulfill()<br>    }<br>        <br>    // then<br>    wait(for: [canceledExpectation, completedExpectation], timeout: 3)<br>}</pre><p>In this test, we’ve set up two expectations, with one of them being set as “inverted.” This means that if the inverted expectation is fulfilled, the test will fail. We then called the <strong>sut.searchWithDebouncer</strong> function twice – the second call cancels out the first. Finally, we use a waiting function that considers both expectations, allowing us to conveniently wait for specific expectations to be met.</p><p>The essence of this test is to confirm that the debouncer effectively handles rapid search calls, ensuring only one can proceed while the other is canceled. It validates the expected behavior of the debouncer implementation.</p><h4>Topic 4: Testing of async/await</h4><p>We won’t delve into the intricacies of the <strong>await</strong> and <strong>async</strong> code structures, as there are plenty of resources available for that. Our main focus here is testing.</p><p>In this example, we’ll fetch an image from <a href="http://unsplash.com/">Unsplash.com</a> and transform the data into a UIImage. Please note that we won’t be addressing the concept of mocking in this context.</p><pre>class CloudService: AnyService {<br>    ...<br>  <br>    func asyncAwaitCall() async throws -&gt; Data {<br>        let url = URL(string: &quot;https://images.unsplash.com/photo-1697208254530-eb42576be354?auto=format&amp;fit=crop&amp;q=80&amp;w=3686&amp;ixlib=rb-4.0.3&amp;ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&quot;)!<br>        let (data, _) = try await URLSession.shared.data(from: url)<br>        <br>        return data<br>    }<br>}<br><br>class DeepOceanViewModel: ObservableObject {<br>    ...<br>    <br>    func callAsyncAwaitCloudService() async throws -&gt; UIImage? {<br>        UIImage(data: try await service.asyncAwaitCall())<br>    }<br>}</pre><p>Thanks to Swift’s concurrency model with <strong>async/await</strong>, writing and testing asynchronous code becomes more straightforward and dependable, resulting in code that&#39;s easier to understand and verify.</p><pre>// 1<br>func test_DeepOceanViewModel_callAsyncAwaitCloudService_didGetImage() async {<br>    // when<br>    let image = try? await sut.callAsyncAwaitCloudService()<br>    <br>    // then<br>    XCTAssertNotNil(image)<br>}</pre><p>To test a structured concurrency function, simply add <strong>async</strong> after the test case, and it handles the asynchronous aspects automatically. You can write the code as if it were synchronous. In this test, we&#39;re fetching an image from the function and checking if it&#39;s not nil. If it&#39;s not nil, the test passes.</p><p>Testing with structured concurrency and <strong>async/await</strong> simplifies the process. I absolutely adore how simple this is.</p><h3>Conclusion</h3><p>Congratulations, dear readers, on embarking on the journey of becoming proficient in writing unit tests in asynchronous environments, specifically for iOS. This article marks the fifth and final instalment in our series on testing, and it has been an incredible ride so far. While we may not have covered every aspect of testing, we’ve certainly equipped you with the knowledge and skills needed to confidently assert your expertise in iOS testing.</p><p>As we wrap up this series, let’s take a moment to reflect on what you’ve learned. You’ve delved into the world of unit and UI testing, tried your first Snapshot tests, mocked different services from expensive calls and finally tackled with asynchronous testing challenges, and honed your skills to become a true testing maestro. Your newfound knowledge will empower you to create robust, reliable code, ensuring that your iOS apps run smoothly and bug-free.</p><p>Remember, becoming an expert is a journey, and practice makes perfect. So, don’t stop here. Continue writing tests, exploring new testing techniques, and pushing your boundaries. With each test you write, you’re not only improving your code but also building confidence in your testing prowess.</p><p>In the world of iOS development, where quality and reliability are paramount, your expertise in testing will set you apart. Your dedication to honing your testing skills will not only benefit your own projects but also the broader iOS community. So, go forth and write tests with confidence, and watch your reputation as a testing expert grow. Here’s to a bug-free future in iOS development!</p><h3>Find it a good read?</h3><p>Recommend this post by clicking the 👏 button so other people can see it and I will be happy to stay connected on LinkedIn <a href="https://www.linkedin.com/in/asilbekdjamaldinov/"><strong>asilbekdjamaldinov</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9efec1c20ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Dev Must-Have: Snapshot Testing]]></title>
            <link>https://medium.com/@asilbekdjamaldinov/ios-dev-must-have-snapshot-testing-0cc78d9b7ef9?source=rss-db3fa83d07d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cc78d9b7ef9</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ui-testing]]></category>
            <dc:creator><![CDATA[Asilbek Djamaldinov]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 11:27:13 GMT</pubDate>
            <atom:updated>2023-10-28T23:25:00.062Z</atom:updated>
            <content:encoded><![CDATA[<p>Here are my other articles of the Testing Flow in iOS :</p><ol><li><a href="https://medium.com/p/b097d1819fa6">Testing in iOS: From Zero to Hero!</a></li><li><a href="https://medium.com/p/ba1b34f1d09e#994c-18d6620e7f4d">Unlocking the Power of UI Testing in iOS Development</a></li><li><a href="https://medium.com/@asilbekdjamaldinov/why-mocking-matters-in-ios-unit-testing-9c6ee4a7241b">Why Mocking Matters in iOS Unit Testing</a></li><li>iOS Dev Must-Have: Snapshot Testing (Current)</li><li><a href="https://medium.com/@asilbekdjamaldinov/why-to-unit-test-in-async-mode-b9efec1c20ef">Why to Unit Test in Async Mode</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Y10bCjYE0FdOprjNRqIgg.jpeg" /></figure><p>Why is snapshot testing important? What does it bring to the table that other testing methods may not?</p><p>To answer this question, imagine you’re an architect designing a grand skyscraper. Every blueprint, every angle, and every material choice must align perfectly to create a visually stunning and structurally sound building. The same holds true for an iOS app — except you’re not just an architect; you’re the engineer, designer, and quality control all rolled into one.</p><p>Snapshot testing in iOS acts like a watchful guardian, ensuring that the design and user interface of your app remain as captivating and error-free as your initial vision.</p><p>In this article, we’ll explore why snapshot testing is crucial for iOS app development. We’ll see how it maintains your app’s visual integrity, minimizes the chances of visual issues cropping up, and why it’s essential for delivering a smooth and polished user experience. Let’s uncover the reasons why snapshot testing is a must for your iOS app development journey.</p><h3>What is Snapshot testing?</h3><p>Snapshot testing is a type of automated testing used in software development, including iOS app development. It focuses on ensuring that the visual appearance and consistency of the user interface (UI) in your app remain unchanged.</p><p>Here’s how snapshot testing works: When you create a snapshot test, it takes an initial “snapshot” of a specific UI component or screen in your app. This snapshot is like a picture or a detailed representation of how the UI looks at that moment.</p><p>When you run a snapshot test, it compares the current state of the UI component to the stored snapshot. If they match exactly, the test passes. But if there are any differences, the test fails.</p><p>If the test fails because you intentionally made changes to the UI, you can choose to update the stored snapshot to match the new UI appearance. This process is controlled and deliberate, ensuring you review and approve any changes as part of the testing.</p><p>Snapshot testing is particularly useful for making sure that UI elements in your app maintain a consistent look. It’s valuable for catching any unintended visual changes that might occur as you work on your app’s code or modify its UI components.</p><h3>A Step-by-Step Guide to Setting Up Snapshot Testing in iOS</h3><p>No more chit-chat! It’s time to dig into the code and have an enjoyable time while working with snapshot testing. 😄</p><h4>App Inspection: Let’s Take a Look</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WeXHa8G3kmBNYBn-yB6DUw.jpeg" /></figure><p>In our app, we’ve got two screens. The first screen is where you find a list of jokes related to programming and testing. You can even hit a button to mix up the jokes and get a fresh set. The second screen is all about the jokes themselves — just a single joke text right in the middle. It’s that simple!</p><p>In our app, we’ve got a view model <strong>DeepOceanViewModel</strong> with just one job. It talks to something called a networking service <strong>NetworkService</strong>. We&#39;ll talk more about this networking service later in the article, when we discuss mocking in snapshot testing. (If you&#39;re unfamiliar with what mocking is and how to put it into practice, I suggest reading my earlier <a href="https://medium.com/@asilbekdjamaldinov/why-mocking-matters-in-ios-unit-testing-9c6ee4a7241b">article</a> on the topic).</p><pre>class DeepOceanViewModel: ObservableObject {<br>    @Published var list: [String] = []<br>    <br>    private let networkService: AnyNetworkService<br>    <br>    init(networkService: AnyNetworkService = NetworkService()) {<br>        self.networkService = networkService<br>        <br>        getList()<br>    }<br>    <br>    func getList() {<br>        list = networkService.fetchList()<br>    }<br>}<br><br>class NetworkService: AnyNetworkService {<br>    // Imagine here that we are making a real networking call<br>    func fetchList() -&gt; [String] {<br>        let list = [<br>            &quot;When your code refuses to work, just blame it on cosmic rays!&quot;,<br>            &quot;Debugging is like being the detective in a crime movie where you&#39;re also the murderer.&quot;,<br>            &quot;Real programmers count from 0. Or at least until they hit 1.&quot;,<br>            &quot;Why do programmers always mix up Christmas and Halloween? Because Oct 31 == Dec 25.&quot;,<br>            &quot;Why do programmers prefer iOS development? Because it&#39;s the only place where an &#39;apple&#39; a day keeps the bugs away!&quot;,<br>            &quot;The best code is the one you don&#39;t have to write. Also, it&#39;s the one you don&#39;t have to test!&quot;,<br>            &quot;Why did the programmer go broke? Because he used up all his cache!&quot;,<br>            &quot;I asked the computer for a joke, and it replied, &#39;Why don&#39;t programmers like nature? It has too many bugs.&#39;&quot;,<br>            &quot;Programming is 10% writing code and 90% figuring out why that code doesn&#39;t work.&quot;,<br>            &quot;You know you&#39;re a programmer when you spend more time Googling error messages than writing code.&quot;<br>        ]<br>        <br>        return list<br>    }<br>}</pre><h4>The plan is as follows:</h4><ol><li>Add a snapshot testing library and directory into the project.</li><li>Create a snapshot test for the main screen.</li><li>Generate a new snapshot with an updated view.</li><li>Compose a test for the subview.</li><li>Mocking the network to run a test without causing changes.</li></ol><h4>Step 1: Snapshot Tool Integration.</h4><p>To begin, we should create a new target for snapshot testing. While you can use the UI test target, I prefer having distinct targets for unit tests, UI tests (XCTests), and UI Snapshot tests. You can do this by going to your project, clicking the ‘+’ button, selecting “unit testing bundle”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*baSO1Cf_vGQD2-xF50h22Q.png" /></figure><p>Name it “YourProjectSnapshotTests.” If you’re unsure how to add a new target, you can refer to <a href="https://developer.apple.com/documentation/xcode/configuring-a-new-target-in-your-project">this</a> for guidance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOsI9qkWytUS6PX7IQ1ZnQ.png" /></figure><p>Your list of targets should now appear like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*yooG2taykPy6MY1bf_T54w.png" /></figure><p>Next, we’ll include the <a href="https://github.com/pointfreeco/swift-snapshot-testing">Swift Snapshot Tests package</a> in our project. I’ll be using Swift Package Manager (SPM) to handle dependencies, but you can also use a POD file if you prefer. The critical step is to integrate this library and specify the target for <strong>YourProjectSnapshotTests</strong>.</p><p>If you skip this part, your project won’t work, and you’ll encounter compile-time errors. You can find detailed instructions on adding dependencies to the specific target in <a href="https://alexandersandberg.com/articles/managing-package-dependencies-with-swift-package-manager-in-xcode/#adding-a-package-dependency-to-multiple-targets">this article</a>.</p><p>My project’s navigation panel appears like this, and yours should match it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*3vi3uIowpWrqfe9mcI4fzQ.png" /></figure><h4>Step 2: Main Screen Snapshot</h4><p>In the “MyOceanSnapshotTests” Swift file, remove all the existing code, and replace it with the following code:</p><pre>import XCTest<br>// 1<br>import SnapshotTesting<br>@testable import MyOceanTests<br><br>final class MyOceanSnapshotTests: XCTestCase {<br>    func test_DeepOceanView_didNotChange() {<br>        // 2<br>        // given<br>        let viewModel = DeepOceanViewModel()<br>        let view = DeepOceanView(viewModel: viewModel)<br><br>        // 3<br>        // then<br>        assertSnapshot(of: view, as: .image)<br>    }<br>}</pre><p>If you’ve read my <a href="https://medium.com/@asilbekdjamaldinov/testing-in-ios-from-zero-to-hero-b097d1819fa6">previous article</a> on unit tests, you’ll notice that snapshot tests are quite similar to unit tests. In fact, the code for snapshot tests closely resembles that of unit tests. It’s a fantastic, isn’t it?</p><p>Let’s take a closer look at what’s happening here:</p><ol><li>SnapshotTesting is the library we added in the first step by importing it into our package. We import it here so that we can use it in our tests.</li><li>In this section, we create instances of the <strong>DeepOceanViewModel</strong> and <strong>DeepOceanView</strong>. The <strong>view</strong> is the actual user interface component that you want to capture in the snapshot test.</li><li>This part of the code executes the snapshot test. It uses the <strong>assertSnapshot</strong> function to capture a snapshot of the <strong>view</strong>. The format in which you want to capture the snapshot is specified as <strong>.image</strong>. The <strong>assertSnapshot</strong> function compares the current state of the <strong>view</strong> to a previously stored snapshot and determines whether they match. If they match, the test passes; if there are differences, it fails, indicating a visual regression that needs to be addressed.</li></ol><p>You might wonder about the “previously stored snapshot.” In reality, there isn’t one, which is why if we run our test now, it will fail. However, the good news is that when we run the test for the first time, it will fail but create a snapshot. Then, when we run it for the second time, we’ll have a snapshot to compare with the current state of the view.</p><p>Now it’s time to give it a shot. Run the test, and you’ll see it fail. But run it again, and this time, it will succeed (I hope so 😁).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhOMnYHZ4xA8B17DRBi0MQ.jpeg" /></figure><p>Once everything runs successfully, you can navigate to your project directory at “…/YourProject/YourProjectSnapshotTests/<strong>Snapshots</strong>/…” to find your very first snapshot. Hooray! Congratulations on creating your first snapshot test.</p><p>And now, if you decide to make changes to your main screen, your test will compare the updated screen with the snapshot you have. It will fail because they won’t be the same. This is a good thing because it prevents unintentional changes. But you might be wondering, “How do we make intentional changes from now on?” Well, the next step is an exciting one, and it will answer that question for you!</p><h4>Step 3: Snapshot Refresh Process</h4><p>Now that we’ve learned how to create a snapshot and what it looks like, let’s make a change to our view. We’ll switch the colour of button from blue to red and run the test again. What do you expect the result will be? Naturally, it will fail. So, let’s add the additional line to our test case:</p><pre>func test_DeepOceanView_didNotChange() {<br>    // given<br>    let viewModel = DeepOceanViewModel()<br>    let view = DeepOceanView(viewModel: viewModel)<br>        <br>    isRecording = true<br>        <br>    // then<br>    assertSnapshot(of: view, as: .image)<br>}</pre><p>Setting isRecording to true is like saying, “Hey, we’re here to capture a new snapshot, and it’s okay if the current test fails because we’re creating a fresh state.” That’s exactly what this line of code does. Ha-ha! 😄</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*78e_lb00gQXjwI5ce0r1pw.jpeg" /></figure><p>After you update the snapshot, be sure to remove the <strong>isRecording</strong> line. And don&#39;t worry if you forget; it&#39;ll kindly remind you. That&#39;s why it&#39;s so user-friendly!</p><p>You can also set <strong>isRecording</strong> to true within an assertion, like this:</p><pre>assertSnapshot(of: view, as: .image, record: true)</pre><p>But it accomplishes the same task as setting <strong>isRecording</strong> to true. So, go ahead and pick the one you like best.</p><h4>Step 4: Subview Snapshot</h4><p>Likewise, we can generate a snapshot for a subview in a similar manner. Under your initial test, include the following code:</p><pre>func test_JokeView_didNotChange() {<br>    let view = JokeView(joke: &quot;Hello friend!&quot;)<br>        <br>    assertSnapshot(of: view, as: .image)<br>}</pre><p>Run the test, and it will fail. Run it again, and it will succeed. I wish all my issues were resolved this easily! 😄. Here what we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b88pIGiYu6v4VUcxQF-OLg.png" /></figure><p>I won’t explain how to write a snapshot test for the second screen because it’s quite similar. However, I want to emphasise that the organisation of your tests depends on your project’s structure. Personally, I like to create separate files for each screen. For instance, if I have three different screens, I’ll have three separate test Swift files. But you’re free to choose the approach that suits you best.</p><p>Now, let’s dive into mocking — it’s an exciting topic!</p><h4>Step 5: Simulating Network Behaviour</h4><p>Let’s take a moment to discuss our list of jokes. Right now, our test works perfectly because it’s based on the same set of jokes we have in our list. However, imagine if the jokes on the server (backend) change, and we receive a different list. That would create a problem because our snapshot contains different jokes compared to the ones from the network.</p><p>The solution is to mock our network interactions. By doing this, we ensure that we always get the same list of jokes returned, making our code rely on something concrete and not subject to unpredictable changes.</p><blockquote>If you’re not sure about what mocking is, I suggest you read my <a href="https://medium.com/@asilbekdjamaldinov/why-mocking-matters-in-ios-unit-testing-9c6ee4a7241b">previous article</a> on the topic. It will provide a helpful explanation.</blockquote><p>We’ll employ a technique called polymorphism to simulate our networking layer using a component named “MockNetworkingService.” This component will be configured to return specific static text as a response. And after, we can recreate the snapshot for the list of jokes on the main view.</p><p>Create a “MockNetworkingService” under the “MyOceanSnapshotTests” target within the “MockServices” directory. Then, add the provided code below:</p><pre>import Foundation<br>@testable import MyOceanTests<br><br>class MockNetworkService: AnyNetworkService {<br>    func fetchList() -&gt; [String] {<br>        return [<br>            &quot;Why did the iOS developer go broke? Because they had too many connections, but none of them were personal!&quot;,<br>            &quot;What do you call a group of iOS developers working on a networking project? The Inter-NETworking Team!&quot;,<br>            &quot;Why did the Wi-Fi network apply for a job? Because it wanted to make better connections!&quot;<br>        ]<br>    }<br>}</pre><p>What this code does is simply provide you with three jokes without going through the actual network. It’s a straightforward process.</p><p>Replace the <strong>viewModel</strong> in your first test case with the code provided below:</p><pre>func test_DeepOceanView_isSame() {<br>    let viewModel = DeepOceanViewModel(networkService: MockNetworkService())<br>    <br>    ...<br>}</pre><p>You’ve essentially created a new instance of your view model, but this time, it’s configured to work with the mock networking service. Create a new snapshot with <strong>isRecording.</strong></p><p>Whew, we’ve come a long way, and you’ve done an excellent job! But before we conclude, there’s one important point to remember.</p><blockquote><strong>When testing snapshots, always stick with one simulator. You can’t use an iPhone 15 Pro today and switch to an iPhone 15 Pro Max tomorrow. Changing simulators will detect differences, and all your tests will fail. It might require a bit of coordination when working with a larger team, but it’s worth discussing which simulator to use for successful snapshot tests.</strong></blockquote><p>You could, of course, add your snapshots to gitignore, but I prefer not to do this. When I create a view, I know exactly how it should look, and I want to save my team the time of verifying if their snapshots are correct. So, with that, we can wrap things up! 😄</p><h3>Conclusion</h3><p>To sum it up with a smile, snapshot testing is like having a trusty guardian for your iOS app’s looks. It ensures that your app always dazzles with the same eye-catching design, sparing you from unexpected visual hiccups. By following a well-organised process, you can boldly tackle UI updates, simplify your testing routine, and serve up iOS apps that are not just glitch-free but also visually delightful.</p><h3>Find it a good read?</h3><p>Recommend this post by clicking the 👏 button so other people can see it and let’s connect on LinkedIn <a href="https://www.linkedin.com/in/asilbekdjamaldinov/"><strong>asilbekdjamaldinov</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cc78d9b7ef9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Mocking Matters in iOS Unit Testing]]></title>
            <link>https://medium.com/@asilbekdjamaldinov/why-mocking-matters-in-ios-unit-testing-9c6ee4a7241b?source=rss-db3fa83d07d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c6ee4a7241b</guid>
            <category><![CDATA[xctest]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Asilbek Djamaldinov]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 21:51:58 GMT</pubDate>
            <atom:updated>2023-10-28T23:23:55.857Z</atom:updated>
            <content:encoded><![CDATA[<p>Here are my other articles of the Testing Flow in iOS :</p><ol><li><a href="https://medium.com/p/b097d1819fa6">Testing in iOS: From Zero to Hero!</a></li><li><a href="https://medium.com/p/ba1b34f1d09e#994c-18d6620e7f4d">Unlocking the Power of UI Testing in iOS Development</a></li><li>Why Mocking Matters in iOS Unit Testing (Current)</li><li><a href="https://medium.com/@asilbekdjamaldinov/ios-dev-must-have-snapshot-testing-0cc78d9b7ef9">iOS Dev Must-Have: Snapshot Testing</a></li><li><a href="https://medium.com/@asilbekdjamaldinov/why-to-unit-test-in-async-mode-b9efec1c20ef">Why to Unit Test in Async Mode</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JsmJgnY09XRq44mDls2RlA.jpeg" /></figure><p>Imagine you’re building an iOS app, and it needs to fetch data from the internet, which takes a long 5 seconds each time you test. But, in your app, there are many places where this happens. Now, when you want to test your code, waiting for these slow downloads can be frustrating. To avoid this, we use a cool trick called mocking.</p><p>Mocking means we fake the internet service and make our tests run super fast on our own computer. It’s like playing with toy data instead of waiting for the real stuff. So, you can quickly check if your code works without getting bored waiting for the internet. It’s like a shortcut to happy and speedy testing!</p><p>In this article, we’ll talk about why pretending or “mocking” is a big deal when testing stuff in iOS apps. So, let’s dive into why this is so awesome! 😄</p><h3><strong>What is Mocking?</strong></h3><p>Mocking is a testing technique used to isolate and evaluate individual components of your code. In iOS development, this typically means creating mock objects to stand in for real objects or dependencies that your code interacts with. These mock objects mimic the behaviour of the real ones but allow you to control and observe interactions during testing.</p><p>The cool part is we can watch and control what happens when we test our code. It’s like having a test double that does what we want.</p><h3>The Need for Mocking</h3><h4>Isolation and Control</h4><p>Unit tests are designed to focus on the behavior of a single unit or component of your code, such as a function, method, or class. Mocking is essential for isolating this unit from its dependencies. By replacing these dependencies with mock objects, you can precisely control the conditions under which your unit is tested. This isolation ensures that any failures are due to issues within the unit itself and not its dependencies.</p><h4>Predictable Testing</h4><p>Mocking allows you to simulate various scenarios, edge cases, and error conditions. You can program these mock objects to produce specific responses, errors, or exceptions, ensuring that your code handles these situations correctly. This predictability is critical for verifying that your unit functions as expected under different circumstances.</p><h4>Speed and Efficiency</h4><p>Real dependencies, like network requests or databases, can be slow, unreliable, or costly to access during testing. By using mock objects, you eliminate the need to interact with these resources, making your unit tests faster and more efficient. This means you can run tests frequently during development without incurring the overhead of real-world dependencies.</p><h3>How to Implement Mocking in iOS Unit Testing</h3><p>Alright, enough talk! Let’s roll up our sleeves, dive into the code, and have some fun getting our hands a bit dirty. 😄</p><h4>Code Safari: Let’s look what we have</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HGWyJCkieX8LH-jvQTBRiA.jpeg" /></figure><p>We’ve got a button on the main screen that, when you press it, downloads a photo and shows it on the screen. To make it more exciting, we’ll even add a little nap for our app, making it sleep for 5 seconds!</p><pre>class NetworkService {<br>    func loooongNetworkCall(_ completion: @escaping (Result&lt;UIImage, Error&gt;) -&gt; ()) {<br>        sleep(5)<br>        <br>        // Open source photo from https://unsplash.com<br>        let request = URLRequest(url: URL(string: &quot;https://unsplash.com/photos/XVoyX7l9ocY/download?ixid=M3wxMjA3fDB8MXxzZWFyY2h8OHx8c2NvdGxhbmR8ZW58MHx8fHwxNjk3NTA5MTQ4fDA&amp;force=true&amp;w=640&quot;)!)<br>        let task = URLSession.shared.dataTask(with: request) { data, _, error in<br>            if let data, let image = UIImage(data: data) {<br>                completion(.success(image))<br>            } else if let error {<br>                completion(.failure(error))<br>            }<br>        }<br>        <br>        task.resume()<br>    }<br>}</pre><p>This piece of code is like a recipe for your app to do something special. It’s all about getting a picture from the internet and showing it on your screen. But, to make things interesting, it pretends to take a little nap for 5 seconds.</p><p>Here’s what’s happening:</p><ol><li>We have a function called <strong>loooongNetworkCall</strong>, which means it&#39;s going to take some time to finish. It needs a special helper (the completion handler) to tell us when it&#39;s done.</li><li>The code first pretends to sleep for 5 seconds. It’s like your app is taking a quick snooze.</li><li>Then, it sends a request to the internet to fetch a picture. The URL in the code tells it where to find the picture online.</li><li>After a while, when it gets a response, it checks if everything went well. If it did, it gives us the picture. If something went wrong, it tells us there was an error.</li></ol><p>So, this code is like a little adventure where our app takes a 5-second nap, goes on the internet to find a picture, and then either shows you the picture or says, “Oops, something didn’t go as planned!”</p><p>Today’s SUT (system under testing) is <strong>DeepOceanViewModel</strong></p><pre>class DeepOceanViewModel: ObservableObject {<br>    @Published var uiImage: UIImage?<br>    @Published var error: Error?<br>    <br>    private let networkService = NetworkService()<br>    <br>    func downloadWallpaper() {<br>        networkService.loooongNetworkCall { [weak self] result in<br>            guard let self else { return }<br>            <br>            switch result {<br>            case .success(let uiImage):<br>                DispatchQueue.main.async {<br>                    self.uiImage = uiImage<br>                }<br>            case .failure(let error):<br>                self.error = error<br>            }<br>        }<br>    }<br>}</pre><p>When you tap the button, it tells the app to download an image from the internet using the <strong>NetworkService</strong>. Once the download is complete, it will either display the image if it was successful or show an error message if something went wrong.</p><p>For testing purposes, we’ll create a pretend version of <strong>NetworkService</strong> to make sure everything works correctly without needing to access the internet. This way, we can check if the app behaves as expected when you press the button.</p><h4>What is a plan?</h4><p>Having a handy plan in your hand is like having a cheerful road map to guide you through your adventure. Let’s write our steps:</p><ol><li>We’ll begin by making a set of rules (a protocol) for both the real <strong>NetworkService</strong> and our pretend version called <strong>MockNetworkService</strong>.</li><li>Then, we’ll change the way we set up the <strong>DeepOceanViewModel</strong> so we can easily put in the pretend service from the outside.</li><li>Next, we’ll create our pretend <strong>MockNetworkService</strong> and teach it how to act.</li><li>We’ll get busy writing tests to check if everything works as expected.</li><li>And, when we’re done, we’ll tidy up and make sure everything is nice and clean.</li></ol><p>This plan helps us make our code better and more reliable!</p><h4>Step 1: Why we need a protocol?</h4><p>We’re adding protocols to our app for a specific reason: so that both our real NetworkService and the pretend MockNetworkService speak the same language and follow the same rules. This way, we can switch between them without any trouble, like swapping parts in a toy set, thanks to a cool concept called “polymorphism” in programming.</p><pre>protocol AnyNetworkService {<br>    func loooongNetworkCall(_ completion: @escaping (Result&lt;UIImage, Error&gt;) -&gt; ())<br>}</pre><p>In this code, we’re defining a protocol called <strong>AnyNetworkService</strong> that sets the rules for any network service that wants to conform to it.</p><p>Here’s what it’s saying:</p><ul><li>It requires a function called <strong>loooongNetworkCall</strong> that takes a completion handler as a parameter.</li><li>This <strong>loooongNetworkCall</strong> function should accept a closure that takes a <strong>Result</strong> object, which contains either an <strong>UIImage</strong> (if everything goes well) or an <strong>Error</strong> (if there&#39;s a problem).</li></ul><p>By creating this protocol, we’re establishing a common set of rules that any network service must follow. This makes it easier to use different network services interchangeably in our code, as long as they adhere to these rules. It’s all about making our code flexible and consistent!</p><p>And eventually, we’ll make sure that our <strong>NetworkService</strong> follows the rules laid out in the <strong>AnyNetworkService</strong> protocol. In other words, <strong>NetworkService</strong> will promise to do what the protocol requires:</p><pre>class NetworkService: AnyNetworkService {<br>  ...<br>}</pre><h4>Step 2: Injecting AnyNetworkService into DeepOceanViewModel</h4><pre>class DeepOceanViewModel: ObservableObject {<br>		...<br>    <br>    private let networkService: AnyNetworkService<br>    <br>    init(networkService: AnyNetworkService) {<br>        self.networkService = networkService<br>    }<br>    <br>    ...<br>}</pre><p>In this updated <strong>DeepOceanViewModel</strong> code, we&#39;re introducing a new way to set up the <strong>networkService</strong> by accepting it as a parameter in the view model&#39;s constructor (init method). Here&#39;s what&#39;s happening:</p><ol><li>We declare a private property <strong>networkService</strong> of the type <strong>AnyNetworkService</strong>. This means we can use any object that conforms to the <strong>AnyNetworkService</strong> protocol as our network service.</li><li>In the constructor (<strong>init</strong>), we require the caller to provide an object that follows the <strong>AnyNetworkService</strong> protocol as an argument. This is often referred to as &quot;dependency injection.&quot; By doing this, we make it flexible to use either the real network service or a mock version (like <strong>MockNetworkService</strong>) depending on the context.</li></ol><p>This change allows us to easily switch between different network services while creating the <strong>DeepOceanViewModel</strong>.</p><h4>Step 3: Crafting MockNetworkService Behaviour</h4><p>In this chapter, we’re diving into the world of creating a “pretend” version of our network service, known as the <strong>MockNetworkService</strong>. The goal here is to make it act just like a real network service but under our complete control. Why do we need this? Well, it&#39;s all about making testing easier and more efficient.</p><p>We’ll be wearing our developer hats and teaching the <strong>MockNetworkService</strong> how to respond to our requests. For example, we&#39;ll make it return images or errors as if they&#39;re coming from a real network. This way, we can mimic different scenarios and see how our app behaves, all without waiting for the real internet.</p><p>Think of it as setting up a virtual playground where we can create various situations and test how our app handles them. So, let’s roll up our sleeves and start crafting the behavior of our pretend network service!</p><p>To begin, open your unit test directory and create a new folder called “MockServices.” Inside this folder, create a Swift file named <strong>“MockNetworkService”</strong>. Here’s what it should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*c-QY9Bs-2Bo5dMbpe1Sj5g.png" /></figure><p>And replace code inside with the following:</p><pre>import XCTest<br>@testable import MyOceanTests<br><br>final class MyOceanTestsTests: XCTestCase {<br>    // 1<br>    var sut: DeepOceanViewModel!<br>    var mockNetworkService: MockNetworkService!<br>     <br>    override func setUp() {<br>        super.setUp()<br>        <br>        // 2<br>        mockNetworkService = MockNetworkService()<br>        sut = DeepOceanViewModel(networkService: mockNetworkService)<br>    }<br><br>    override func tearDown() {<br>        // 3<br>        sut = nil<br>        mockNetworkService = nil<br>        <br>        super.tearDown()<br>    }<br>}</pre><ol><li>Here, we’re setting up our test case for <strong>DeepOceanViewModel</strong>. We declare two properties, <strong>sut</strong> (System Under Test, which is the view model we&#39;re testing) and <strong>mockNetworkService</strong> (our pretend network service).</li><li>In the <strong>setUp</strong> method, which runs before each test, we initialize our <strong>mockNetworkService</strong> by creating an instance of <strong>MockNetworkService</strong>. We also set up our <strong>sut</strong> (DeepOceanViewModel) with the <strong>mockNetworkService</strong>. This ensures that our view model uses the mock service during testing.</li><li>The <strong>tearDown</strong> method, which runs after each test, is used to clean up resources. Here, we release references to <strong>sut</strong>and <strong>mockNetworkService</strong> to ensure they don&#39;t interfere with subsequent tests.</li></ol><p>This setup allows us to create a clean environment for each test case, ensuring that any changes made during one test won’t impact the next test. It’s an essential part of unit testing to maintain consistency and isolate test cases.</p><h4>Step 4: Testing Download Photo Functionality</h4><p>At the end of your unit test class, add this test case:</p><pre>// 1<br>func test_DeepOceanViewModel_downloadUserPhoto_didGetImage() {<br>    // given<br>    let expectation = XCTestExpectation(description: #function)<br>        <br>    // when<br>    sut.downloadUserPhoto()<br>        <br>    let listener = sut.$uiImage.dropFirst().sink { _ in<br>        expectation.fulfill()<br>    }<br>        <br>    wait(for: [expectation], timeout: 3)<br>        <br>    // then<br>    XCTAssertNotNil(sut.uiImage)<br>}</pre><p>You don’t need to focus too much on the expectation and wait lines here. These lines are one of the ways to test asynchronous behaviour, and we’ll dive deeper into this topic in future articles.</p><p>Let’s break down the code:</p><ol><li>We’re starting a test for the <strong>DeepOceanViewModel</strong> function called <strong>downloadUserPhoto()</strong>. This test checks whether the view model can successfully obtain a user&#39;s photo.</li><li>In “given” section, we set up an <strong>expectation</strong> using <strong>XCTestExpectation</strong>. This expectation is like a promise that the test will wait for something to happen before it finishes. We give it a description based on the test function&#39;s name.</li><li>In the “when” section, we call <strong>sut.downloadUserPhoto()</strong>, which simulates the action of downloading a user&#39;s photo.</li><li>We create a <strong>listener</strong> using the <strong>$uiImage</strong> property of <strong>sut</strong>. When it emit changes, we fulfill our expectation.</li><li>We’re using <strong>wait(for:timeout:)</strong> to wait for the expectation to come true. Specifically, we&#39;re waiting for a maximum of 3 seconds to see if the image gets downloaded. If nothing happens within 3 seconds, we consider the test as failed.</li><li>In the “then” section, we make an assertion using <strong>XCTAssertNotNil</strong> to check if the <strong>uiImage</strong> property of <strong>sut</strong> is not <strong>nil</strong>. If it&#39;s not <strong>nil</strong>, the test passes, indicating that we were able to download an image successfully.</li></ol><p>This test verifies whether the <strong>DeepOceanViewModel</strong> can indeed download a user&#39;s photo and whether the <strong>uiImage</strong> property is updated as expected.</p><p>Hooray! We’ve done it! We’ve cleverly pretended with our network stuff to speed up our testing. Try it out, and feel proud of your fantastic work. You’ve done an awesome job! 🎉</p><h4>Step 5: Wrapping Up and Cleaning</h4><p>You might be wondering, “Hey, Asilbek, we’ve tested the successful scenario, but what about testing when things go wrong?” That’s a great question, and I’m glad you’re thinking along with me. The cool thing is, we’re in charge of our pretend network, so we can use our special powers to make it misbehave for our tests. 😄</p><p>What we’re planning is to make a special variable inside our mock network service that we can adjust. Depending on this variable, we’ll make the mock service behave differently and return the right result to test different cases.</p><p>Change your <strong>mockNetworkService :</strong></p><pre>class MockNetworkService: AnyNetworkService {<br>    var isSuccessCase: Bool = true<br>    <br>    func loooongNetworkCall(_ completion: @escaping (Result&lt;UIImage, Error&gt;) -&gt; ()) {<br>        if isSuccessCase {<br>            completion(.success(UIImage()))<br>        } else {<br>            completion(.failure(NetworkError.failure))<br>        }<br>    }<br>}</pre><p>If the <strong>isSuccessCase</strong> is set to true, we&#39;ll make the mock return the successful scenario. If it&#39;s not true, we&#39;ll make it send an error instead.</p><p>Add new test case to your unit test class:</p><pre>func test_DeepOceanViewModel_downloadUserPhoto_didGetError() {<br>    // given<br>    // 1<br>    mockNetworkService.isSuccessCase = false<br>    let expectation = XCTestExpectation(description: #function)<br>        <br>    // when<br>    sut.downloadUserPhoto()<br>     <br>    // 2<br>    let listener = sut.$error.sink { _ in<br>        expectation.fulfill()<br>    }<br>        <br>    wait(for: [expectation], timeout: 3)<br>        <br>    // then<br>    // 3<br>    XCTAssertNotNil(sut.error)<br>}</pre><p>Let’s go through the test code step by step, based on the comment numbers:</p><ol><li>We’re starting a test to check how the <strong>DeepOceanViewModel</strong> behaves when it encounters an error during the download process. We set the <strong>isSuccessCase</strong> variable of the <strong>mockNetworkService</strong> to <strong>false</strong>. This indicates that we want the mock service to simulate a scenario where there&#39;s an error.</li><li>In the “then” section, we check whether the <strong>error</strong> property of the view model (<strong>sut</strong>) is not <strong>nil</strong>. If it&#39;s not <strong>nil</strong>, the test passes. This indicates that the view model successfully detected and stored an error, as expected.</li></ol><p>This test checks if the <strong>DeepOceanViewModel</strong> responds correctly when the <strong>mockNetworkService</strong> is set to return an error instead of a successful scenario during the download. It&#39;s essential to ensure that the view model handles error cases properly.</p><h3>Conclusion</h3><p>In a nutshell, mocking is a vital tool in iOS unit testing. It helps you break down and thoroughly examine different parts of your code. By using mock objects, you can make sure your code works correctly under different scenarios while keeping your tests fast and cost-effective. Incorporating mocking into your testing process is a smart approach that can result in more dependable and easier-to-maintain iOS applications. It’s a serious practice that serious developers should consider.</p><h3>Find it a good read?</h3><p>Recommend this post by clicking the 👏 button so other people can see it and let’s connect on LinkedIn <a href="https://www.linkedin.com/in/asilbekdjamaldinov/"><strong>asilbekdjamaldinov</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c6ee4a7241b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of UI Testing in iOS]]></title>
            <link>https://medium.com/@asilbekdjamaldinov/unlocking-the-power-of-ui-testing-in-ios-ba1b34f1d09e?source=rss-db3fa83d07d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba1b34f1d09e</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[ui-testing]]></category>
            <dc:creator><![CDATA[Asilbek Djamaldinov]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 07:02:03 GMT</pubDate>
            <atom:updated>2023-10-28T23:24:50.174Z</atom:updated>
            <content:encoded><![CDATA[<p>Here are my articles of the Testing Flow in iOS :</p><ol><li><a href="https://medium.com/p/b097d1819fa6">Testing in iOS: From Zero to Hero!</a></li><li>Unlocking the Power of UI Testing in iOS Development (current)</li><li><a href="https://medium.com/p/9c6ee4a7241b">Why Mocking Matters in iOS Unit Testing</a></li><li><a href="https://medium.com/@asilbekdjamaldinov/ios-dev-must-have-snapshot-testing-0cc78d9b7ef9">iOS Dev Must-Have: Snapshot Testing</a></li><li><a href="https://medium.com/@asilbekdjamaldinov/why-to-unit-test-in-async-mode-b9efec1c20ef">Why to Unit Test in Async Mode</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEa4N59yYBc4lLcy_DBzig.jpeg" /></figure><p>In our previous <a href="https://medium.com/@asilbekdjamaldinov/testing-in-ios-from-zero-to-hero-b097d1819fa6">article</a>, we delved into the world of iOS testing. We learned about different types of tests, including unit tests and UI tests, and explored how to incorporate them into your app using Xcode. We even got our hands dirty by writing some basic unit tests. Now, let’s continue our journey by focusing on UI tests and understanding what they are all about.</p><h4>Why to use UI Tests?</h4><p>UI tests, short for User Interface tests, are like the inspectors of your app’s graphical user interface (GUI). They are designed to examine how your app’s interface behaves and ensure it functions as expected when users interact with it. UI tests simulate real user interactions and help you spot any hiccups or glitches in your app’s visual elements and user experience.</p><h4>Navigating the UI Testing Waters in MyOceanTest</h4><p>In our Xcode project, which we used in last article, we’ll be working with a special directory called the “MyOceanTestsUITests”. This directory is like a treasure trove where we store all our UI tests. It’s the place where we create and manage our UI test files.</p><blockquote>If you’re new to iOS testing and haven’t had the chance to peruse my previous <a href="https://medium.com/@asilbekdjamaldinov/testing-in-ios-from-zero-to-hero-b097d1819fa6">article</a>, I strongly encourage you to do so. It’ll provide you with valuable insights and background information that will enhance your understanding of the testing in the article</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*aseP_y4LB-orwUvF-onxrg.jpeg" /></figure><p>As you can see in the screenshot, we have a dedicated folder named <strong>“MyOceanTestsUITests”</strong> within our <strong>“MyOceanTests”</strong> project. This is where we’ll be adding our UI test files.</p><p>Think of this folder as your underwater treasure chest, where each UI test you write is like a precious gem, helping to keep your app shipshape and user-friendly.</p><h4>Exploring the Depths of Default UI Testing Files in Xcode</h4><p>Earlier, we talked about the basic files you get when you create unit tests in Xcode. Now, when it comes to UI tests, it’s pretty similar, but there are a few differences. Let’s focus on those differences.</p><pre>import XCTest<br><br>final class MyOceanTestsUITests: XCTestCase {<br><br>    override func setUp() {<br>    super.setUp() {<br>        // 1<br>        continueAfterFailure = false<br>    }<br><br>    override func tearDown() {<br>        super.tearDown()<br>    }<br><br>    func testExample() throws {<br>        // UI tests must launch the application that they test.<br>        // 2<br>        let app = XCUIApplication()<br>        app.launch()<br>        // Use XCTAssert and related functions to verify your tests produce the correct results.<br>    }<br><br>    // 3<br>    func testLaunchPerformance() throws {<br>        if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {<br>            // This measures how long it takes to launch your application.<br>            measure(metrics: [XCTApplicationLaunchMetric()]) {<br>                XCUIApplication().launch()<br>            }<br>        }<br>    }<br>}</pre><ol><li>The <strong>setUp()</strong> and <strong>tearDown()</strong> functions in UI tests work just like they did in unit tests. They run before and after each test to get things ready and clean up afterward.<br>But there’s something interesting in the code: **continueAfterFailure = false.** What this does is, it tells the test to stop running if it encounters a problem or failure. In simpler terms, it&#39;s like saying, “Hey, if something goes wrong, don&#39;t keep going, just pause and let me fix it”. If just one test doesn&#39;t work as expected, the entire testing process will come to a halt and make it very clear that something went wrong.<br>If you set it to <strong>true</strong>, it will keep going and finish running all the tests, even if one of them fails. It won&#39;t stop and try to cover all ui tests.<br>I like to tackle problems right away, so most of the time, I set it to <strong>false</strong> because it allows me to address issue immediately.</li><li>We have a function named <strong>func testExample() throws.</strong> Inside the function we create a special thing called <strong>app</strong>using <strong>XCUIApplication()</strong>. This <strong>app</strong> represents our app (the whole app) that we want to test.<br>Then, <strong>app.launch()</strong> make our app launch, just like how you&#39;d start an app on your phone or computer. This function is like turning on our app and getting it ready for testing. We&#39;re preparing to interact with it and check if everything works as it should.</li><li>This code is all about measuring how quickly our app launches, like how fast it starts when you open it.<br>Here’s what’s happening step by step:<br>1. <strong>measure(metrics: [XCTApplicationLaunchMetric()]) { ... }</strong>: This part sets up a measurement. We&#39;re telling Xcode, &quot;Hey, we want to measure something.&quot; In this case, we&#39;re measuring how long it takes for our app to launch.<br>2. Inside the <strong>{ ... }</strong> part: <strong>XCUIApplication().launch()</strong>: This line starts our app. It&#39;s like pressing the &quot;Start&quot; button on your app. We&#39;re making the app begin running.</li></ol><p>So, when we run this code, it will keep track of how many seconds it takes for our app to start, and it will give us that information. This is important because fast app launches make for a smoother and more enjoyable user experience.</p><blockquote>We’ll explore this topic more thoroughly in our next article when we dive deeper into UI testing.</blockquote><h4><strong>Get Ready to Dive into UI Testing Sea</strong></h4><p>Enough! Theory is great, but nothing beats getting your hands dirty with some real code. Let’s dive in and start writing some UI tests to see how it all comes together in practice. It’s where the real fun begins! 🚀</p><blockquote>Certainly, explaining UI testing is simpler in video, but I’ll do my best to make it as clear as possible using text.</blockquote><h4>Uncovering Hidden Treasure</h4><p>Let’s see what we’ll be testing today. 🥳</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rWmMxC2mVM6IY1YrPIDlXg.jpeg" /></figure><blockquote>I’m not just any designer; I’m a professional designer, believe me! 😉</blockquote><p>We’ve got a handful of things to test here:</p><ol><li>We’ll make sure the “Registration” text is present.</li><li>Then, we’ll check if the text field works and opens the soft keyboard.</li><li>We’ll examine a button that shouldn’t function when the username field is empty but should navigate when there’s text.</li><li>And, of course, we’ll check the back button.</li></ol><p>I think that’s a good amount for our initial testing. Excited? Me too.</p><h4>Last thing before we actually start.</h4><p>There’s this amazing feature that makes our work way easier. It lets us click on things in our app, and it does the code-writing part for us (thanks, Apple!). To use it, open your UITest file, move your mouse cursor to the line where you want to write your test, and find the red circle button with ‘Record UI Test’ written on it in the bottom-left corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x2YLSC6b7lpiuuYNH-X0Gw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*aioTwACOdHMURpCPoJCuZA.png" /></figure><p>When you click that button, your app will start running, and you can interact with it by clicking on different items. As you do, it records the actions you take, creating a sequence of steps. Later, you can use this recorded sequence to create your UI test. It’s like building a path of actions that the test will follow.</p><p>After clicking on the “Registration” text multiple times, you’ll notice that inside the function, something like this appears:</p><pre>func test_deepOceanView_textRegistration_isPresent() {  <br>    let registrationStaticText = XCUIApplication().staticTexts[&quot;Registration&quot;]<br>    registrationStaticText.tap()<br>    registrationStaticText.tap()<br>    registrationStaticText.tap()<br>}</pre><p>In line let registrationStaticText = … Xcode creates a reference to the UI element with the label “Registration.” It’s like pointing to that specific text on the screen. Next, we’re tapping on the “Registration” text three times in a row and Xcode creates a record. Each tap simulates a user interaction with that text.</p><p>By using this approach, you can mimic any actions or steps a user might take within your app’s logic.</p><h4>Don’t Forget Your Testing Toolkit</h4><p>Before we jump into the testing, let’s check our gear:</p><ol><li><strong>Xcode</strong>: Our virtual submarine for exploring the code sea.</li><li><strong>XCTest</strong>: Our trusty harpoon for tagging and capturing bugs.</li><li><strong>Record UI Test Button:</strong> This nifty button helps us record our testing actions.</li><li><strong>Coffee</strong>: Our essential underwater oxygen supply (just kidding, it’s for staying awake during late-night bug hunts). 😁</li></ol><h4>A Tiny Step for Mankind, But a Giant Leap in UITest Learning!</h4><p>Great news! We’ve already talked about the “given — when — then” pattern for testing in iOS, and the good news is that we’ll keep using this pattern in UI tests as well. It’s a consistent and effective way to structure our tests.</p><p>In the test mentioned above, we have three actions. First, in the “given” part, we create a property called <strong>registrationStaticText</strong>. Then, we perform the <strong>.tap()</strong> action, but we&#39;ll disregard it because we used it to reference the text itself, not for testing the assertion of its presence. Finally, in the &quot;then&quot; part, we perform the assertion itself.</p><p>When it’s all said and done, our test will have the following structure:</p><pre>func test_deepOceanView_textRegistration_isPresent() {<br>    // given<br>    let app = XCUIApplication()<br>    app.launch()<br>    let registrationStaticText = app.staticTexts[&quot;Registration&quot;]<br>        <br>    // then<br>    XCTAssertTrue(registrationStaticText.exists, &quot;Text exists&quot;)<br> }</pre><p>You see, <strong>.exists</strong> checks if an element is on the screen. It gives us a simple &quot;true&quot; or &quot;false&quot; answer, and we can use <strong>XCTAssertTrue</strong> to verify whether it&#39;s indeed true or not.</p><p>Click the diamond icon next to your <strong>func test_...</strong> to run your test and see if it works. (I&#39;ll let you in on a secret — it will work!)</p><p>Let’s move on to the second test. We’ll name it <strong>test_deepOceanView_usernameTextField_didCallKeyboard</strong>. Once again, run the magical red button, click on the text field, and let Xcode do the work of generating the code to start the test. Here’s the final version of the test with the assertion:</p><pre>func test_deepOceanView_usernameTextField_didCallKeyboard() {<br>    // given<br>    let app = XCUIApplication()<br>    app.launch()<br>    let textField = app.textFields[&quot;Username&quot;]<br>    <br>    // Make sure the keyboard is not initially displayed<br>    XCTAssertFalse(app.keyboards.element.exists, &quot;Keyboard is not initially visible&quot;)<br>        <br>    // when<br>    textField.tap()<br>        <br>    // then<br>    // Now, check if the keyboard is displayed<br>    XCTAssertTrue(app.keyboards.element.exists, &quot;Keyboard is visible after tapping the text field&quot;)<br>}</pre><p>This test first verifies that the text field exists, then checks if the keyboard is initially hidden, taps on the text field to trigger the keyboard, and finally confirms that the keyboard is visible after tapping.</p><p>Not too challenging, is it?</p><p>Let’s dive into the third test case. We’ll be testing two scenarios:</p><ol><li>We’ll check a button that shouldn’t do anything when the username field is empty (no navigation).</li><li>We’ll verify that it does navigate when there’s text in the username field.</li></ol><p>This is interesting because in my code, I’ve added a condition <strong>if !username.isEmpty { ... }</strong> to prevent navigation from working when the username is empty. So, it should be an interesting test to run.</p><p>We will start from the second test case. Let’s give your new test a name: <strong>test_deepOceanView_signupButton_didMakeNavigation</strong>. Once again, follow the same steps as before: run the magical red button, click on the text field, and tap on the keyboard buttons to interact with the UI. Let Xcode generate the code to initiate this test.</p><pre>func test_shallowOceanView_signupButton_didMakeNavigation() {<br>    // given<br>    let app = XCUIApplication()<br>    app.launch()<br>    let textField = app.textFields[&quot;Username&quot;]<br>    textField.tap()<br>    <br>    // when<br>    let AKey = app.keys[&quot;A&quot;]<br>    AKey.tap()<br>    <br>    let aKey = app.keys[&quot;a&quot;]<br>    aKey.tap()<br>    aKey.tap()<br>    <br>    app.buttons[&quot;Sign Up&quot;].tap()<br>    <br>    // then<br>    let helloWorldStaticText = app.staticTexts[&quot;Hello world&quot;]<br>    XCTAssertTrue(helloWorldStaticText.exists, &quot;Hello world exists&quot;)<br>}</pre><p>We simulate typing “Aaa” into the text field by tapping the appropriate keyboard keys. After that, we tap the “Sign Up” button, triggering a navigation action. Then we verify that the “Hello world” static text exists on the screen after the navigation. This is our assertion, confirming that the navigation worked as expected.</p><p>For the first case, we’ll follow the same steps, except this time, we won’t tap any keyboard buttons. Instead, we’ll directly tap the “Sign Up” button. In this scenario, navigation should not work, and we shouldn’t see the “Hello world” text. That’s why we switch our assertion from confirming test case is true to checking that it’s false.</p><pre>func test_shallowOceanView_signupButton_didNotMakeNavigation() {<br>    // given<br>    let app = XCUIApplication()<br>    app.launch()<br>    let textField = app.textFields[&quot;Username&quot;]<br>    textField.tap()<br>    <br>    // when<br>    app.buttons[&quot;Sign Up&quot;].tap()<br>    <br>    // then<br>    let helloWorldStaticText = app.staticTexts[&quot;Hello world&quot;]<br>    XCTAssertFalse(helloWorldStaticText.exists, &quot;Hello world exists&quot;)<br>}</pre><p>The final test case in this article is checking whether the back button functions correctly. We’ll name it <strong>test_shallowOceanView_backButton_didNavigateBack()</strong>. The process of generating code will be the same as in our previous test cases. We’ll tap the back button to verify if it works as expected.</p><pre>func test_shallowOceanView_backButton_didNavigateBack() {<br>    // given<br>    let app = XCUIApplication()<br>    app.launch()<br>    let textField = app.textFields[&quot;Username&quot;]<br>    textField.tap()<br>    <br>    let AKey = app.keys[&quot;A&quot;]<br>    AKey.tap()<br>    <br>    let aKey = app.keys[&quot;a&quot;]<br>    aKey.tap()<br>    aKey.tap()<br>    <br>    app.buttons[&quot;Sign Up&quot;].tap()<br>    <br>    let helloWorldStaticText = app.staticTexts[&quot;Hello world&quot;]<br>    XCTAssertTrue(helloWorldStaticText.exists, &quot;Hello world exists&quot;)<br>  <br>  // when<br>  app.navigationBars[&quot;Shallow Ocean View&quot;].buttons[&quot;Back&quot;].tap()<br><br>  // then <br>  let registrationStaticText = app.staticTexts[&quot;Registration&quot;]<br>  XCTAssertTrue(registrationStaticText.exists, &quot;Text exists&quot;)<br>}</pre><p>After pressing the back button on the ShallowOceanView, we verified our location by checking if the “Registration” text is present. This text should be on the main page where we expect to navigate back to.</p><p>Phew! That was quite the adventure, but we nailed it! 😅</p><h4>Tests’ code optimisation</h4><p>We have an opportunity to streamline our code significantly, but we’ll save most of those optimisations for our next UITesting article. For now, let’s simplify things by moving the let app = XCUIApplication() and app.launch()lines from each method into a class variable and launch the app in the setUp() method.</p><pre>final class MyOceanTestsUITests: XCTestCase {<br>    let app = XCUIApplication()<br>        <br>    override func setUp() {<br>        app.launch()<br>        continueAfterFailure = false<br>    }<br>  <br>  ...<br>}</pre><p>Make sure to tidy up your test methods. Run the tests in your UITest file and take a look at the outcome. You’ve done fantastic work!</p><h4>Conclusion</h4><p>In conclusion, UI testing is a crucial aspect of iOS app development, allowing us to ensure that our app’s user interface functions as expected. By creating UI tests in Xcode and following the “given — when — then” pattern, we can thoroughly examine different aspects of our app’s user experience.</p><p>This article provided an overview of UI testing in iOS development, demonstrated how to set up UI tests in Xcode, and walked through several practical test cases. While there’s more to explore in UI testing, this article laid the foundation for conducting effective tests and improving the quality of iOS apps. So, get ready to dive deeper into the exciting world of UI testing in your iOS development journey! 🚀</p><h3>Find it a good read?</h3><p>Recommend this post by clicking the 👏 button so other people can see it and let’s connect on LinkedIn <a href="https://www.linkedin.com/in/asilbekdjamaldinov/"><strong>asilbekdjamaldinov</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba1b34f1d09e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing in iOS: From Zero to Hero!]]></title>
            <link>https://medium.com/@asilbekdjamaldinov/testing-in-ios-from-zero-to-hero-b097d1819fa6?source=rss-db3fa83d07d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b097d1819fa6</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Asilbek Djamaldinov]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 21:14:48 GMT</pubDate>
            <atom:updated>2023-10-28T23:25:20.926Z</atom:updated>
            <content:encoded><![CDATA[<p>Here are my articles of the Testing Flow in iOS :</p><ol><li>Testing in iOS: From Zero to Hero! (current)</li><li><a href="https://medium.com/@asilbekdjamaldinov/unlocking-the-power-of-ui-testing-in-ios-ba1b34f1d09e">Unlocking the Power of UI Testing in iOS Development</a></li><li><a href="https://medium.com/p/9c6ee4a7241b">Why Mocking Matters in iOS Unit Testing</a></li><li><a href="https://medium.com/@asilbekdjamaldinov/ios-dev-must-have-snapshot-testing-0cc78d9b7ef9">iOS Dev Must-Have: Snapshot Testing</a></li><li><a href="https://medium.com/@asilbekdjamaldinov/why-to-unit-test-in-async-mode-b9efec1c20ef">Why to Unit Test in Async Mode</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wuz3AL3lglpESQkIg4x3AA.jpeg" /></figure><p>Imagine your boss is about to give a big presentation to some super important people with deep pockets, and just as he’s about to impress them with your app, it goes haywire! 😱 That’s like baking a perfect cake, but it falls apart right before you serve it to your guests. Testing helps you avoid this “baking disaster” and ensures your boss’s presentation goes off without a hitch!</p><h3>Testing in iOS</h3><p>Testing in iOS is like constructing a sturdy skyscraper, and it relies on three essential building blocks:</p><ol><li><strong>Unit Testing</strong>: This is where we ensure that each individual brick (or piece of code, mostly functions) is strong and reliable. It’s like checking that every component, like the elevators or the air conditioning, works perfectly before assembling the whole building.</li><li><strong>Integration Tests</strong>: These are like checking that different parts of our skyscraper fit together seamlessly. We examine how the elevators interact with the electrical systems, making sure everything works in harmony.</li><li><strong>UI Tests</strong>: Here, we put ourselves in the shoes of the people who will live and work in our skyscraper. We check that the windows provide a beautiful view, the doors open smoothly, and everything looks and functions as expected. It’s like ensuring the skyscraper is not just functional but also aesthetically pleasing.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BuGzc1JgGSk1u45QZmTQAg.png" /></figure><p>By building on these three pillars of testing, we can construct iOS apps that are not only robust but also provide a fantastic user experience — just like a skyscraper that stands tall and impresses everyone who sees it.</p><p><em>Another essential type of test is the performance test. These tests evaluate how efficiently your app runs, similar to checking your car’s performance. They help identify any issues, like slow loading times, ensuring your app remains speedy and responsive, even during demanding tasks. But let’s leave it for a while. We will come to it in later parts, I promise.</em></p><p>Theory is great, but nothing beats getting your hands dirty with some real code. Let’s dive in and start writing some tests to see how it all comes together in practice. It’s where the real fun begins! 🚀</p><h3>Making First “Waves”: Adding Tests to Your iOS Project</h3><p>Imagine you’re starting a new project in Xcode, and you want tests from the get-go. Well, there’s this magical option when you create your project.</p><ol><li><strong>Create Your Project:</strong> Fire up Xcode, and when you’re creating your new project, keep an eye out for that cheeky little checkbox that says, “Include Tests.”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bseqRjs-C0sTicTpJlWJ9g.jpeg" /></figure><ol><li><strong>Tick That Box:</strong> Don’t be shy! Go ahead and tick that box. It’s like saying, “Yes, I want some testing goodness right here!” 🎉</li><li><strong>Xcode Does the Rest:</strong> Once you’ve checked the box, Xcode works its Abracadabra (magic — hope you get it). It creates a whole testing playground for you, complete with test files ready to roll. 🎩✨</li></ol><p>And that’s it! You’ve added tests to your project without breaking a sweat.</p><h4>Testing Waters Explored: A Dive into Tests’ Directories and Files</h4><p>Let’s take a closer look at the files added by Xcode in the <em>“YourProjectNameTests”</em> and <em>“YourProjectNameUITests” </em>directory, where you’ll add files for unit and ui tests respectively for your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*dgQneZZeD9wzl0HboQbb6Q.jpeg" /></figure><h4>XCTestCase class</h4><p>Additionally, Xcode automatically takes care of some of the heavy lifting for you. Here’s how it works in simplified terms:</p><pre>// 1<br>import XCTest<br><br>// 2<br>final class MyOceanTestsTests: XCTestCase {<br>  // Auto-generated code. We will cover it shortly.<br>}</pre><ol><li><strong>Import XCTest:</strong> Think of this as inviting a special guest to your app’s party. By importing XCTest, you’re telling Xcode that you want to include testing capabilities.</li><li><strong>Create Test Class and inherits from XCTestCase:</strong> Xcode goes a step further and creates a test class for you. This class is like your testing playground, ready for all your testing adventures. Your test class is not just any class; it inherits from XCTestCase. Think of this inheritance as your class learning the secret testing handshake. It means your class can now write and run tests using XCTest’s powerful tools.</li></ol><p>So, by adding tests during app creation, Xcode sets up the stage for your testing journey, making it easier to start testing your app right from the beginning!</p><h4>setUp() and tearDown()</h4><p>In both unit tests and UI tests, there are special methods for setting up and tearing down the testing environment to ensure a clean and consistent state for each test. These methods play a crucial role in the testing process:</p><pre>...<br><br>final class MyOceanTestsTests: XCTestCase {<br>    // 1<br>    override func setUp() {<br>        // This method is called BEFORE each individual test.<br>    }<br><br>    // 2<br>    override func tearDown() {<br>        // This method is called AFTER each individual test.<br>    }<br>}</pre><ol><li><strong>setUp():</strong> This method is called before each individual test. It’s like preparing the stage before an actor’s performance. You can use it to initialise any necessary objects or resources needed for your test. <strong>setUpWithError():</strong> this is the same as setUp(), but if something goes wrong during the setup, it can throw an error even before your test begins.</li><li><strong>tearDown():</strong> Conversely, this method is called after each test has executed. It’s like clearing the stage after the act. You can use it to release any resources or clean up any changes made during the test, ensuring a clean slate for the next test. <strong>tearDownWithError():</strong> this is the same as tearDown(), but if something goes wrong during the clean up, it can throw an error.</li></ol><blockquote>Methods are called every time before and after execution.</blockquote><p>It’s like having your test’s backstage team, ensuring everything’s in order before and after the spotlight shines on your code!</p><h3>A Shallow Dive into the Deep Waters of Unit Testing</h3><h4>Our Testing Toolkit</h4><p>Before we jump into the testing waters, let’s check our gear:</p><ol><li><strong>Xcode</strong>: Our virtual submarine for exploring the code sea.</li><li><strong>XCTest</strong>: Our trusty harpoon for tagging and capturing bugs.</li><li><strong>Coffee</strong>: Our essential underwater oxygen supply (just kidding, it’s for staying awake during late-night bug hunts). 😁</li></ol><h4>Start from small fish</h4><p>Let’s dive into testing a simple and understandable function, shall we?</p><p>Imagine you have a small ViewModel, I will call it “DeepOceanViewModel”, and inside it, there’s a function called “sum.” This function takes two parameters, let’s call them “a” and “b,” and it does something really straightforward — it adds them together!</p><pre>class DeepOceanViewModel {<br>    func sum(_ a: Int, _ b: Int) -&gt; Int {<br>        a + b<br>    }<br>}</pre><p>Now, we want to test this function to make sure it’s adding correctly. We’ll create some test cases to check if the “sum” function behaves as expected.</p><p>In our “MyOceanTestsTests” class, we’ll write test methods to check different scenarios. For example, we might have a test method like this:</p><pre>// 1<br>func test_sumPositiveNumbers() {<br>  // 2<br>  // given<br>  // 3<br>  let sut = DeepOceanViewModel() // Create an instance of your DeepOceanViewModel<br>  let a = 3<br>  let b = 5<br><br>  // when<br>  let result = sut.sum(a, b) // Call the sum function with 3 and 5<br>    <br>  // 4<br>  // then<br>  XCTAssertEqual(result, 8, &quot;Sum of 3 and 5 should be 8&quot;) // Check if the result is as expected<br>}</pre><p>Let’s figure out what is happening here.</p><ol><li>When you’re naming your test functions, always kick them off with the magic word “test.” This tells the compiler, “Hey, this is a test case!” It doesn’t matter if you follow it with “_”, “Sum,” or anything else, as long as it starts with “test.” So, it’s like the secret code to let the computer know, “Get ready to run a test!”</li><li><strong>“given,” “when,” and “then”</strong> comments are a great practice for documenting your test’s structure and purpose. They make your test more readable and help others (and future you) understand what’s happening at each stage of the test.</li><li><strong>What is SUT?</strong> Here, “sut” is an abbreviation for “System Under Test,” and you’re creating an instance of your DeepOceanViewModel class to test it. In other words, “sut” represents the instance of your view model that you’re subjecting to testing within this particular test case. Using “sut” as a variable name is a common practice in unit testing to make your test code more readable and explicit. It clearly indicates which part of your code you’re focusing on during the test.</li><li><strong>“XCTAssertEqual”</strong> is specifically used to check if two values are equal. It’s a way to verify that the actual result of an operation in your test is equal to the expected result. There are different Assertions in XCTest library such as: XCTAssertTrue, XCTAssertFalse, XCTAssertNil, XCTAssertNotNil, etc.</li></ol><p>The test function name, when properly named, serves as a clear and informative description of what the test is doing. In this case, “test_sumPositiveNumbers” can be read as:</p><p>📌 “It is a function to test the result of the sum of two positive numbers. Our system under testing is DeepOceanViewModel with given constants a = 3 and b =5. When we call function sut.sum(a, b) we get “result” and then we compare sum of a + b and the result of sut.sum(a, b)”.</p><p>In XCTest, the test function indicator uses a color code to let you know whether your test passed or failed:</p><ul><li><strong>Green Diamond:</strong> When your test runs, and all assertions within the test pass successfully, you’ll see a green diamond. This indicates that your test case has succeeded, and everything is working as expected.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XSEyDz0Fwqn9KVQACbxQQ.png" /></figure><ul><li><strong>Red Diamond:</strong> If any assertion within your test fails, the diamond turns red. This is a clear visual indicator that something went wrong during the test, and you need to investigate the issue. <br>When a test fails and the diamond turns red, XCTest provides a clear and helpful message to indicate why the test didn’t succeed. This message is essential for diagnosing the issue quickly and efficiently.</li></ul><p>For example, in our test case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69Xhb_D-ylDzDBuOfacQJA.png" /></figure><p>If the actual result of the <strong>multiply</strong> function is not equal to 12 (i.e., the test fails), XCTest will display the message &quot;Multiplication of 4 and 3 should be 12&quot; alongside the failure notification. This message serves as a diagnostic aid, letting you know what you expected and what the actual result was.</p><p>The color-coded feedback makes it easy to quickly identify the status of your tests and catch any issues early in the development process. It’s like having a traffic light for your code, telling you when it’s safe to proceed (green) and when you need to stop and fix something (red).</p><p>Let’s try another test:</p><pre>class DeepOceanViewModel {<br>    func sum(_ a: Int, _ b: Int) -&gt; Int {<br>        ...<br>    }<br>    <br>    func multiply(_ a: Int, _ b: Int) -&gt; Int {<br>        a * b<br>    }<br>}</pre><p>As you understand we are going to test function “multiply(a, b)”. Here’s the corresponding unit test:</p><pre>func test_multiplyPositiveNumbers() {<br>    // given<br>    let sut = DeepOceanViewModel() // Create an instance of your DeepOceanViewModel<br>    let a = 4<br>    let b = 3<br><br>    // when<br>    let result = sut.multiply(a, b) // Call the multiply function with 4 and 3<br><br>    // then<br>    XCTAssertEqual(result, 12, &quot;Multiplication of 4 and 3 should be 12&quot;)<br>}</pre><p>It is not so difficult, isn’t it? In fact, it’s a valuable practice that can save you a lot of time and headaches in the long run.</p><h3>Diving Deep into Test Efficiency</h3><p>Remember when I told you about the setup and teardown methods? Well, it’s time to put that knowledge into action.</p><p>What’s common in these two tests? You guessed it — the “System Under Test” (SUT), which is your <strong>DeepOceanViewModel</strong>. We&#39;re going to be smart about it and move the creation of the SUT into the setup method and any cleanup stuff into teardown.</p><p>Why? Because it makes our tests cleaner, less repetitive, and follows good coding practices. So, it’s like tidying up our testing room and making sure everything is in its place!</p><p>Let’s start by declaring our main character, the <strong>DeepOceanViewModel</strong>, as a variable named <strong>sut</strong> (System Under Test) right at the beginning of our test class.</p><pre>final class MyOceanTestsTests: XCTestCase {<br>    var sut: DeepOceanViewModel! // Define sut<br> <br>  // Other code<br>  ...<br>}</pre><p>It’s totally safe to force-unwrap <strong>DeepOceanViewModel</strong> with <strong>!</strong> because we&#39;re initializing it in the <strong>setUp</strong> method before every test. This makes it not only safe but also much more convenient to use.</p><p>Think of it like having your trusty equipment set up on stage before every performance. You know it’s there, ready to go, so you can confidently use it without worrying about it being absent.</p><pre>final class MyOceanTestsTests: XCTestCase {<br>  var sut: DeepOceanViewModel! <br><br>  override func setUp() {<br>      super.setUp()<br>      sut = DeepOceanViewModel() // Initialize sut<br>  }<br>    <br>  override func tearDown() {<br>      sut = nil // Clean up sut<br>      super.tearDown()<br>  }<br><br>  ...<br>}</pre><p>In the <strong>setUp</strong> method, we&#39;ll give life to our <strong>sut</strong> by initializing it, getting it ready for action.</p><p>And when it’s time to wrap up the show, in the <strong>tearDown</strong> method, we&#39;ll bid farewell to our <strong>sut</strong>, making sure everything is tidy and cleaned up.</p><p>Remember the golden rule: We create our testing star, <strong>sut</strong> (System Under Test), right after we&#39;ve set up the stage with <strong>super.setUp()</strong>. And just before the curtains close in <strong>tearDown()</strong>, we bid farewell to <strong>sut</strong> by setting it to <strong>nil</strong>. This way, <strong>sut</strong> is always ready to perform during the tests and gracefully exits when it&#39;s time to wrap things up.</p><p>This way, <strong>sut</strong> is like the star of our testing show, always ready for action and gracefully bowing out after each performance.</p><p>The final step is to make sure you remove the initialization of <strong>sut</strong> from your test methods. In other words, you don&#39;t need to create <strong>sut</strong> separately inside each test anymore because you&#39;ve already set it up in the <strong>setUp</strong> method. This keeps your tests clean and follows the &quot;DRY&quot; (Don&#39;t Repeat Yourself) principle, making them more efficient and easier to maintain.</p><h3>Conclusion</h3><p>In the vast ocean of software development, testing is your trusty compass, guiding your app safely through turbulent waters. We’ve explored the importance of testing in iOS, delving into unit tests. We’ve witnessed how bugs can make a grand entrance when you least expect them, even during your boss’s crucial presentation.</p><p>We navigated the seas of XCTest, learning about unit tests, UI tests, and performance tests. Performance tests, like an app’s fitness check-up, keep it zippy and responsive, even when faced with heavy lifting.</p><p>And let’s not forget the ‘System Under Test’ (SUT), our star performer. We’ve optimized our tests by initializing SUT in <strong>setUp</strong> and cleaning up in <strong>tearDown</strong>, following the golden rule.</p><p>That’s just the beginning of our journey through the world of testing in iOS. We’ve embarked on a marine adventure together, exploring the importance of testing and diving into XCTest.</p><p>But don’t go too far! This is just the first part of our series of articles. I hope you’ve enjoyed our maritime escapade, and I look forward to seeing you in our upcoming adventures.</p><p>Stay tuned, fellow explorers, as we continue to navigate the iOS testing waters. See you soon! 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b097d1819fa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>