<?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 Javier Medina on Medium]]></title>
        <description><![CDATA[Stories by Javier Medina on Medium]]></description>
        <link>https://medium.com/@jvrmed?source=rss-1a10c42961c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*JybWeGVtFuHndjHoFRxWJQ.jpeg</url>
            <title>Stories by Javier Medina on Medium</title>
            <link>https://medium.com/@jvrmed?source=rss-1a10c42961c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 18:35:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jvrmed/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[Progress is better than perfect]]></title>
            <link>https://medium.com/@jvrmed/progress-is-better-than-perfect-390745e70d12?source=rss-1a10c42961c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/390745e70d12</guid>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[goals]]></category>
            <category><![CDATA[time-management]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Javier Medina]]></dc:creator>
            <pubDate>Sat, 11 Jan 2020 22:00:55 GMT</pubDate>
            <atom:updated>2020-01-11T22:00:55.259Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SjCEFfLGamCPLvG3GYByFQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lindsayhenwood?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lindsay Henwood</a> on <a href="https://unsplash.com/s/photos/progress?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>How often do you feel stuck while doing something because you don’t have a clear idea on how to do it right? And how many times you feel like you failed on something because your perfect streak was broken? Your diet failed because of that couple of beers you had with your friend. You haven’t opened the book you wanted to read in weeks and your room is a mess since that weekend you got sick.</p><p>It is very common for me that I set up goals and start quite well with reaching them, but then something happens and after a single miss all the previous successes are immediately discarded and the whole sense of accomplishment crumbles.</p><p>A similar feeling occurs when I have something important to do but I am not completely sure on how to do it. I don’t have an end-to-end plan, therefore it becomes extremely hard to even start doing it. Like a task at work or even to write something. I have an idea, a general goal of what I have to accomplish but I have no clue on how to start. This feeling can last for hours, days or even weeks and it is extremely frustrating as I want to do it but somehow I feel that I can’t even get started.</p><p>I think both scenarios are related to some sort of perfectionism. If you want to go to the gym 3 times a week and then you get injured and have to skip leg day, then the whole momentum of those perfect three weeks before your injury seems ruined. It has to be 3 times a week otherwise you have failed.<br> <br>But why a single miss have such a strong effect in our minds? To be honest I have no idea. But what I know is that after facing this situation many times I have realised a good way to handle it. It all comes down to the following sentence:</p><blockquote>Progress is better than perfect.</blockquote><p>Yeah. Just that. Go ahead and read it once again.</p><p>The thing is, it is extremely naive to thing that for every goal we set we are going to be able to reach it all the times. It is also some sort of self-sabotage to think that every time you want to do something you will nail it immediately.</p><p><strong>If you have a long-term goal in your life you must be able to accept that things are going to get into the way</strong>, but as long as you are taking steps into the direction that you want you should already be proud of yourself. The length of the steps and their frequency can always be adjusted, but the only way to get anywhere is to move.</p><p>Until a couple of weeks ago I thought this reasoning worked only for long-term goals, but recently I have discovered that there is a way to apply it to small daily things that we have to do but that we are not motivated to do. Usually in my case the lack of motivation to do something comes when I don’t know how to start or when I feel overwhelmed by the size of the task and I get stuck by not being able to even imagine the final result.</p><p>The reasoning to overcome this paralysis is quite simple. Break whatever you have to do into smaller pieces and instead of facing a huge task you will be facing dozens of very little and insignificant tasks. For every one of this little pieces that you finish there will be a small sense of accomplishment that will help you moving forward.</p><blockquote>Just keep reminding yourself that whatever progress you have, either on daily tasks or in long-term projects, is worth to be acknowledged.</blockquote><p>So if you have to write an essay your first task could be to create a document for the essay. If you get stuck thinking of a title just drop a casual <em>&quot;Change this for a better title&quot;</em> and move on. Not sure what to write on the first section? Try bullet points. Just a few, then move on. In no time you will have a decent boilerplate of your essay and quite a few ideas on what to develop in each part of it. Then you just have to re-iterate over it a few times and after some polishing you will be done! The same reasoning can be applied to coding, drawing and basically every task that can be split into smaller tasks.</p><p>For both short and long-term goals I think it is very important to keep a sense of achievement that helps us keep moving towards the goal. It doesn’t have to be all or nothing as there are many steps in between that require time, effort and energy to be done. It is true that the final result it is also important for the morale, but the only way to get there is with small steps through the whole path.</p><p>Just keep reminding yourself that whatever progress you have, either on daily tasks or in long-term projects, is worth to be acknowledged. Be kind to yourself when you fail, remember that no journey is perfect and tackle your challenges with small bits at a time and, in no time, you will look back and see how far you have gone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=390745e70d12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three learnings for a Happy New Year]]></title>
            <link>https://medium.com/@jvrmed/three-learnings-for-a-happy-new-year-146c4a633bd?source=rss-1a10c42961c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/146c4a633bd</guid>
            <category><![CDATA[life-change]]></category>
            <category><![CDATA[habits]]></category>
            <category><![CDATA[happiness]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[new-years-resolutions]]></category>
            <dc:creator><![CDATA[Javier Medina]]></dc:creator>
            <pubDate>Tue, 31 Dec 2019 16:21:37 GMT</pubDate>
            <atom:updated>2019-12-31T16:58:08.520Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_u3R5Fj_o5RJpCRNff3uQ.jpeg" /></figure><p>It’s been a while since I don’t write a New Year’s message, but it feels like the time has come to finally do it again because 2019 has been a very intense year and I feel like sharing some learnings. With the new year coming we all want to iron down resolutions and figure out how we can make our life better, so here are three learnings for you to keep in the back of your head that have helped me through this year and I hope it helps you through 2020 and beyond.</p><p>The first one is: <strong>take care of yourself.</strong> And by this I mean both physically, emotionally and mentally. And there is a reason why I am making a distinction between emotionally and mentally here. But let’s break it down.</p><p>Regarding the physical, some people say that we are what we eat. But we also are what we drink, how much we exercise and how much we rest and sleep. There is not a single one of this points that can be overlooked without impacting the general outcome of our health. So if you want to start doing something for yourself in 2020, start by reviewing your habits. Drink more water, avoid added sugar, eat less fried stuff and you will see how your mood changes and you feel like having more energy to do everything in your life. Find a nutritionist if you are struggling on understanding how to have a balanced diet.<br> <br> Once you take care of having good fuel to keep you going, get some time to take care of your mind and your heart. Your thoughts about yourself and about the others can be beneficial for you but they can also take you down and compromise your health if you don’t watch them out. We cannot necessarily control what we feel but we can definitely control how we handle those feelings. If you are struggling with some inner demons and your mind is not giving you any time to rest, look for help. Talk to the ones you love or find a specialist. There is nothing wrong or bad about it. It won’t make you weaker. Instead it will help you grow stronger and to get back the control of your life.</p><p>If someone around you makes you feel bad when you open yourself to them, they are not the right person to help, even that they are your partner, your parents or your best friend. Find the right persons to support you and you will thrive. Invest time, energy and money into balancing your body, your mind and you heart. This is learning number one.</p><p>The second is: <strong>take notes.</strong> The key point here is fairly simple as our mind has a limited capacity to remember and organise stuff, specially on a world full of inputs through social media and beyond.</p><p>This is something I haven’t figured out completely quite yet and it might sound obvious for many, but the chaos I used to feel inside my mind started to feel controlled from the moment I started to dump thoughts, tasks and reminders to paper, apps and alarms. This will help you to understand better all the things you have to do, your deadlines and how to organise around them. This is learning number two.</p><p>The last one is: <strong>you are truly special.</strong> And I am sorry for being so cliche here but it is true. I have no idea what you have gone through during this year and in your life in general, but if there is something that I am sure after my 2019 is that everyone is special in their own way and we all should be aware of that.</p><p>I have realised that some people around me have a great esteem for me and value some skills that I have that I personally don’t value that much or don’t even consider as a talent. I think most of the times we focus on the things we want to improve and specially to acquire rather that the ones we have and this mindset can be very demanding some times.</p><p>So take some time to acknowledge yourself and to thing about the good stuff you have. It might be some skill that you use at work everyday, it might be that you are a good listener or a good cooker. How organised you are. An artistic talent. How kind you are with the ones you don’t know and the amount of patience you have to deal with challenges. Your resilience to believe and fight for the things you want. The amount of people that you inspire in your every day life or even on social media. It can be even those skills that no one sees but yourself. Things about yourself that make you proud of. This is learning number three.<br> <br> So I hope you had a great 2019. I hope you have plenty of health and energy to keep growing, learning and enjoying life during the new year that is coming. That you realise that nothing needs to change at midnight because the changes that really matters happens over the course of our whole lives. <br> <br> I hope you take care of yourself and you revisit your habits so you can enjoy every day better, that you can conquer anxiety and your fears and that you find an effective way to organise yourself through your daily challenges. I hope you recognise your talents and all the special things you have.<br> <br> And after you realise how special you are, take some time to think about how you can give back to the world a bit of that special you, so we can all build a better world together.<br> <br> Enjoy your night and have a happy 2020!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=146c4a633bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 steps to mock third-party services in Swift]]></title>
            <link>https://medium.com/@jvrmed/5-steps-to-mock-third-party-services-in-swift-ff7cdda46165?source=rss-1a10c42961c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff7cdda46165</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[facebook]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Javier Medina]]></dc:creator>
            <pubDate>Sun, 26 Nov 2017 21:39:45 GMT</pubDate>
            <atom:updated>2017-11-26T21:52:09.183Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jSMCPg-LXqJRGqbe_YUQw.jpeg" /></figure><p>Recently I’ve been diving more and more into testing and a lot of questions have popped up, specially regarding how to test third party services. Unless you want to reinvent the wheel all the time, it’s normal (and even expected) that we all use at some point in our code some library or framework that was not developed by ourselves.</p><p>When it comes to that, I started to think that testing the parts of my code that were related to those components was really complicated. However, recently I discovered one approach that it’s quite straightforward and allows mocking of almost everything, so let’s jump into it! If you want, you can find all the code used in this post <a href="https://github.com/jvrmed/facebook-login-mock">here</a>.</p><h3>How it works</h3><p>We all know how flexible and powerful <a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html">protocols</a> can be in <em>Swift</em> and it’s very common to use them when implementing delegates for example. In fact, our dearest UITableViewDataSource and UITableViewDelegate are nothing more than that, protocols waiting to be implemented.</p><p>However, when considering third-party frameworks such as Facebook&#39;s, the implementation is already done and we can&#39;t change it much. Luckily the approach to mock it is quite simple. For this example, I will use Facebook&#39;s login flow to show how we can test different scenarios such as success, cancel and failure and be sure that our app behaves as it should depending on the service&#39;s response.</p><h3>1. Find your interface</h3><p>If you go to <a href="https://developers.facebook.com/docs/swift/login">Facebook’s Swift SDK — Getting Started</a> you will find an example on how to create a custom login button that uses their LoginManager to perform a simple login. The flow is quite simple, given some permissions you can either login successfully, cancel the login flow or get an error. I did some changes to their example to set up different values according to the service response:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5171b81dd3628086e469a9982ae0b01/href">https://medium.com/media/d5171b81dd3628086e469a9982ae0b01/href</a></iframe><p>Considering our own app login flow, what we want to test here is what would happen in our app in every case of Facebook’s login flow: success, user cancel and failure. In other words, to be able to mock the result of the loginManager.logIn call. So the first step is to know the exact interface of that method. To do that, we can use Xcode&#39;s autocomplete to generate it for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OwMa18w1-Gd_Q6S4vOqfUg.png" /></figure><p>Simply use your loginManager variable to see the available methods until your find the one you are interested in. After you select it, you should have something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/542ea7624336bb32fcff0adbda9109c6/href">https://medium.com/media/542ea7624336bb32fcff0adbda9109c6/href</a></iframe><p>But Javier, why you just not look at the Documentation instead of using Xcode to figure out the method signature? It’s an excellent question actually. Sometimes the documentation is enough to find how the interface should be.</p><p>However, depending on how you installed your framework, its possible that you can only access its headers and sometimes those headers are in Objective-C. In this case, if you open <em>FBSDKLoginManager.h</em> you will find the following interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bd3dc2c3fcccbef4a03019125ebe15b/href">https://medium.com/media/8bd3dc2c3fcccbef4a03019125ebe15b/href</a></iframe><p>Since we have optionals and some other important differences between Objective-C and Swift, its easier and quicker just to grab the method signature straight from where we are using it instead of looking around in other dark and ugly places.</p><h3>2. Create a protocol</h3><p>Now that we have the exact interface that the method that we need to mock uses, we can create a protocol with it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c8ac4a13a0991c420ada464bef4d93a/href">https://medium.com/media/3c8ac4a13a0991c420ada464bef4d93a/href</a></iframe><p>So far nothing special. What we are doing here is to create a protocol that, once is adopted by a class, it will implement a method with the same interface that the FBSDKLoginManager uses.</p><h3>3. Extend your third-party service</h3><p>For me this is the magic part. By using <em>Swift</em> extension we can extend (duh!) any kind of object or class with new methods or variables. However, we can also use extensions to standardise interfaces. Since we can’t directly modify some third-party frameworks we can just make them compliant with custom protocols that they already implement by themselves.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d916d32b2c4b4795698cfa5f63d17a3b/href">https://medium.com/media/d916d32b2c4b4795698cfa5f63d17a3b/href</a></iframe><p>What we are doing here is telling our compiler that FBSDKLoginManager complies with FacebookProtocol, hence, it implements all the methods that the protocol defines.</p><p>In general, we make classes conform to a protocol to implement those interfaces, as in the UITableViewDataSource case for example. However, in this case we know that FBSDKLoginManager already implements the logIn method, even that we don&#39;t know how.</p><p>But why do we need a <em>hood</em> interface for our third-party service?</p><h3>4. Replace third-party types</h3><p>Once your protocol is in place its easier to abstract the services among your codebase. What we have to do is to create a single entry point for the third-party service. In this case, instead of using FBSDKLoginManager variables every time we need to perform some login related action, we will create our own service that will keep a single instance of FBSDKLoginManager.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/385f802202abbfd95658473497304658/href">https://medium.com/media/385f802202abbfd95658473497304658/href</a></iframe><p>As you can see, the variable type is FacebookProtocol instead of FBSDKLoginManager but the default value is a FBSDKLoginManager instance. This is possible because of our extension.</p><p>Since FBSDKLoginManager conforms with FacebookProtocol, we can set to our shared instance any class that conforms with that protocol. And now that we have a single instance for our service, we can use it in our code instead of using the third-party constructor directly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d72975e551cb2ec805c5dcb3865da1bf/href">https://medium.com/media/d72975e551cb2ec805c5dcb3865da1bf/href</a></iframe><h3>5. Mock those services</h3><p>Once we have our protocol in place and a single access point for the third-party service we can easily mock them by creating new objects that comply with FacebookProtocol and replacing our FacebookService.sharedInstance with it. By doing this, every part of our code that uses FBSDKLoginManager will call our mock instead and we will be able to check if our app handles responses properly.</p><p>So first of all we create our mock. We will set it up with two variables, one for the expected result and one for possible errors. Those variables are the ones we are going to use to check if the response handler is called properly. Also, we will implement the logIn method to execute the handler with those variables. Don&#39;t forget to make your mock compliant to FacebookProtocol.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69329d297f0c554aa60590bf2c474cad/href">https://medium.com/media/69329d297f0c554aa60590bf2c474cad/href</a></iframe><p>In our test case, we will create some extra variables too so we can store a reference to our mock, to our tested controller and to a token that its required to create a FBSDKLoginManagerResult. In our setUp method we will initialise all those variables and reset our controller&#39;s loginResult back to .none so we ensure the same start point for all tests.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/310f3cf969b9806eaff42e6088d53b40/href">https://medium.com/media/310f3cf969b9806eaff42e6088d53b40/href</a></iframe><p>Last but not least, we create some tests to check if our controller handle the response properly and changes the value of loginResult variable according to the response:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/560ff8e53a4663aef2f56db4f778944b/href">https://medium.com/media/560ff8e53a4663aef2f56db4f778944b/href</a></iframe><p>In these cases we are merely checking if the response was handled properly by using the loginResult variable. However, in real life scenarios we would like to test if error alerts were displayed, if navigation happened property or, for example, if the token that Facebook send us was stored properly.</p><h3>Conclusion</h3><p>I think that testing our codebase is extremely important to ensure quality software. However, by personal experience I know that testing can become a bottleneck during the development cycle if we don’t know exactly what to test or even worst, if we don’t know how to test it.</p><p>With this article I hope to bring some light to those that have faced this challenge at some point and to give insights to to those that want to develop better code.</p><p>I am aware that there are different approaches to this problem but personally this solution has come very handy to me when testing frameworks such as Facebook’s, CoreLocation and AVFoundation so luckily it will be useful for you too.</p><p>Cover Photo by <a href="https://unsplash.com/photos/DfMMzzi3rmg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">William Iven</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff7cdda46165" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing UITableViews DataSource (Part 1)]]></title>
            <link>https://medium.com/@jvrmed/testing-uitableviews-datasource-part-1-1f77a3dc1e90?source=rss-1a10c42961c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f77a3dc1e90</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[uitableview]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Javier Medina]]></dc:creator>
            <pubDate>Tue, 24 Oct 2017 21:23:01 GMT</pubDate>
            <atom:updated>2017-10-26T08:11:22.943Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5w7iWTn6qNjXXDb_4LDEg.jpeg" /></figure><p>Testing apps is a very important task in mobile development, specially when your product needs to be constantly shipped and you are not a one man team.</p><p>However, even than continuous integration is supposed to be the goal since day one, we all know that in the real world most of us jump into projects that were already started by someone else and that have a lot of untested code.</p><p>That considered, this is going to be my first post regarding <strong><em>Code Testing</em></strong> and its all about testing <a href="https://developer.apple.com/documentation/uikit/uitableview">UITableView</a> components in <a href="https://swift.org/">Swift</a>. More specifically about how to test <a href="https://developer.apple.com/reference/uikit/uitableviewdatasource">UITableViewDataSource</a>.</p><p>The main reasons why I choose this topic to start with are the fact that I spend most of my working hours developing in <em>Swift</em> and that <em>UITableViews</em> are one of the most basic components used in any <em>iOS app</em>.</p><h3>Code structure</h3><p>The code regarding this project can be found <a href="https://github.com/jvrmed/ios-todo">here</a> and its composed by a single screen app in which there is an <em>UITableView</em>. Since <em>UITableViews</em> are very complex components and there are many different ways we can use them, this example focuses on how to test the required <em>UITableViewDataSource</em> methods, which are:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebf1830de70cc5e7b083ada613be8bc3/href">https://medium.com/media/ebf1830de70cc5e7b083ada613be8bc3/href</a></iframe><p>If you download and run the code, you will see a screen with empty lines, its scrollable but there is no much to see. I used to think that I needed to <em>see</em> everything that I was doing in order to test it properly.</p><p>After some time I realised that I could decouple logic and UI and test them separately. This could sound like an obvious reasoning but sometimes practise is not as easy as theory.</p><p><strong>TL;DR</strong> If you are more interested in the testing part than the project itself, just refer to the <strong>Testing</strong> session.</p><h3>AppDelegate.swift</h3><p>This is the starting point of our app. It has a lot of boilerplate and normally we don’t need to touch it to start developing anything. However, in this case I wanted to isolate the <em>UIViewController</em> from the storyboard, so I inserted a function to manually set the <em>RootViewController</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9851efcff58aad9c6b4dc46d6077368c/href">https://medium.com/media/9851efcff58aad9c6b4dc46d6077368c/href</a></iframe><p>And the function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c360808fef76b71f9fb0e6a1643e27f/href">https://medium.com/media/5c360808fef76b71f9fb0e6a1643e27f/href</a></iframe><p>What this function does is to create a <em>TodoListViewController</em> instance and set it as our window <em>rootViewController</em>. By doing this we load our app straight into the <em>UIViewController</em> we want to test.</p><p>As an extra of this post we are also going to see how to test that our initial view controller is loaded correctly using a <em>UI Test</em>.</p><h3>TodoListAdapter.swift</h3><p>Since we want to test our <em>UITableViewDataSource</em> properly it is better if we detach it from our <em>UIViewController</em>. To do this we create a separated class to implement the data source protocol. This adapter class could be used to implement <em>UITableView’s</em> delegate too, but that’s out of the scope of this post.</p><p>For now, lets focus on how to implement the data source. Since our adapter’s main goal is to implement the <em>UITableViewDataSource</em> protocol, we need to add that interface to the adapter’s declaration. We also need to add an <em>NSObject</em><strong> </strong>interface because the <em>UITableViewDataSource</em><strong> </strong>requires compliance with <em>NSObjectProtocol</em><strong> </strong>too:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0354611a3461965c4f376c90f987eb49/href">https://medium.com/media/0354611a3461965c4f376c90f987eb49/href</a></iframe><h3>Constants</h3><p>In order to be able to get advantage of <em>iOS</em> memory optimizations we should assign our <em>UITableViewCells</em> an identifier that will allow them to be de-queued and used again when needed, instead of making new allocations every time.</p><p>Since our adapter is going to be the responsible of managing the <em>UITableView</em> content, lets add a constant there that allows us to be consistent among the codebase with the same identifier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c08aa20afc1c0a5c6f6364e42d5f75a4/href">https://medium.com/media/c08aa20afc1c0a5c6f6364e42d5f75a4/href</a></iframe><h3>Variables</h3><p>Since we want to decouple our data from the <em>UIViewController</em>, lets create a variable to store our data inside the adapter and create a proper initializer that receives that data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d8decc03320889aed8e979a47e22cb9/href">https://medium.com/media/1d8decc03320889aed8e979a47e22cb9/href</a></iframe><p>By doing this, every time we create an adapter we can assign it the data that it will be using to render our <em>UITableView</em>. Also, this will be useful for testing, since we can mock our data directly inside the adapter according to our needs.</p><p>For simplicity purposes our data is going to be an array of <em>Strings</em>. In future posts I will explain better how to handle different data types inside an adapter, but for now to use <em>Strings</em> is enough.</p><h3>UITableViewDataSource</h3><p>When testing an <em>UITableViewDataSource</em> we want to be able, fundamentally, to check if the data is loaded properly. As I said before, there are two methods that are required to be implemented in order to do that:</p><ul><li><em>tableView(UITableView, numberOfRowsInSection: Int)</em></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65b65b6256f3b43dd9fc3029a54b14bb/href">https://medium.com/media/65b65b6256f3b43dd9fc3029a54b14bb/href</a></iframe><p>This method is responsible for defining the amount of rows with data that our <em>UITableView</em> has. Since we want to diplay all of our data inside our table view we are going to make it return our <em>data</em> array count.</p><ul><li><em>tableView(UITableView, cellForRowAt: IndexPath)</em></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9952b3227fad51032f27a2f56f7dbd6/href">https://medium.com/media/e9952b3227fad51032f27a2f56f7dbd6/href</a></iframe><p>Once we know how many rows are table is going to have, the <em>data source</em> needs to allocate a <em>UITableViewCell</em> for each one. This is the <em>View</em> that its going to be displayed on each row and its fully customizable. For the purpose of this post we will use a standard <em>UITableViewCell</em>.</p><p>On the <em>let statement</em> we request a cell from the <em>tableView</em>. This method guarantees that a non-nil cell is returned as long as we have in our <em>UITableView</em> the <em>cellIdentifier</em> registered with a <em>UITableViewCell</em> subclass or a custom <em>nib</em>.</p><p>To register our <em>cellIdentifier</em> we need a reference to the <em>UITableView</em> and for the adapter purposes is not useful to have one on it. That said, we are going to register our <em>cellIdentifier</em> in our <em>UIViewController</em>, which has the ownership of the <em>UITableView</em>, therefore, access to it.</p><h3>TodoListViewController.swift and TodoListViewController.xib</h3><p>This is our <em>UIViewController</em> and <em>xib</em> couple. The <em>XIB</em> file is composed by a <em>UIView</em> with a <em>UITableView</em> anchored its margins. Since we are testing a single controller, there is no point in adding other components such as buttons or navigation bars. In the next parts of this post we will make some changes to integrate our <em>UITableView</em> inside more realistic contexts.</p><h3>Outlets</h3><p>Since we are using a <em>xib</em> file, we need to link our <em>UITableView</em> inside our <em>UIViewController</em> by using and <em>outlet</em>. By doing this we will be able to access the UI component from our controller:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57346309dacc263422fc3979f8b59eb2/href">https://medium.com/media/57346309dacc263422fc3979f8b59eb2/href</a></iframe><h3>Variables</h3><p>Regarding variables, our <em>UIViewController</em> just needs an instance of <em>TodoListAdapter</em> :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c40ae444c23c6042fb8ce3dfe0c89f0/href">https://medium.com/media/5c40ae444c23c6042fb8ce3dfe0c89f0/href</a></iframe><p>This variable encapsulates all the protocols that we need to implement to manage our <em>UITableView</em>. Many tutorials and examples implement the <em>UITableViewDataSource</em> within the <em>UIViewController</em> itself. However, this approach makes very difficult to test those components.</p><h3>Accessibility</h3><p>Finally, we create an accessibility struct. This component is going to be responsible for defining all the <em>accessibility labels</em> that we are going to declare within our <em>UIViewController</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27cfd035d79f423e605dcee73351fd63/href">https://medium.com/media/27cfd035d79f423e605dcee73351fd63/href</a></iframe><p>Later in our <em>testing section</em> I will talk more about why is important to define this inside the code and how this struct helps to maintain our codebase.</p><h3>Init, override and setups</h3><p>Once we defined all the outlets, variables, constants and general objects of our <em>UIViewController</em> we can move to its implementation. In this example we are going to override one single method from <em>UIViewController</em> which is <em>viewDidLoad</em>.</p><p>This method should be used to setup all the components according to your needs, as long as those setups doesn’t require layout information. On <em>viewDidLoad</em> we still don’t have our views resized according to the device, since the <em>auto layout</em> functions haven’t been called yet, but we have all the <em>outlets</em> in place and the information that we passed to our <em>UIViewController</em> when we created it (either via <em>xib</em> or manually in a previous controller).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69696836ca88b04254b6f0c185468ef4/href">https://medium.com/media/69696836ca88b04254b6f0c185468ef4/href</a></iframe><p>Personally I like to keep my <em>viewDidLoad</em> methods clean. Instead of adding a bunch of logic to it, I try to separate different setups in <em>fileprivate</em> methods. This is very helpful when we need to quickly understand how a <em>UIViewController</em> is loaded because the name of the setup methods should be self explanatory. Is very easy when we put everything together to mix different components setups, which makes very hard to read the code and to eventually refactor it.</p><p>In this case I have two setup methods, one for the <em>UITableView</em> and one for the <em>accessibility</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b04fa478448427ae71bd32e5f2a046b/href">https://medium.com/media/4b04fa478448427ae71bd32e5f2a046b/href</a></iframe><p>In the first one we do two things: we register an <em>UITableViewCell</em> class in our <em>tableView</em> and setup its <em>dataSource</em> to our <em>adapter</em>. Remember the <em>cellIdentifier</em> that we defined in our <em>TodoListAdapter</em>? Well, we use it here to bind it to the correct cell class. Since we are loading the identifier from the adapter we dont need to worry about changing it later within our adapter, since it won’t break our <em>tableView</em>.</p><p>Also, we can set our <em>TodoListAdapter</em> as the <em>tableView</em> data source thanks to its protocol compliance. Since our adapter implements <em>UITableViewDataSource</em> interface, we can assign it to the <em>UITableView</em> without worrying about casting. One of the advantages of protocol use in <em>Swift</em>.</p><p>The second method is responsible to setting up the <em>tableView’s</em> accessibility label. With this accessibility label we will be able to access the <em>tableView</em> within our <em>UI Tests</em>. Even tho UI Tests are not the scope of this post, I will provide one example on how to do them to verify that our components are in place when the app is running.</p><h3>Testing</h3><p>Finally the fun part, with our code in place we can start testing. If you are used to <strong><em>Test Driven Development (TDD) </em></strong>you will read this and think that everything is wrong since tests should be written first and then the code, and then refactor and then repeat. I totally agree with you. However, the goal of this post is not about how to do <em>TDD</em> when developing in <em>Swift</em> but how to test a specific component. Once you understand how to do it you can <em>TDD</em> it as many times as you want.</p><h3>TodoListAdapter</h3><p>Let’s start with our <em>TodoListAdapterTests</em> class. As the name states, is the set of tests responsible for testing our adapter. This is the main test class of this example since it will test our <em>UITableViewDataSource</em>. Let’s analyze it in parts. First of all we have our variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a7609d8dfa8294c012de75067adb1a5/href">https://medium.com/media/3a7609d8dfa8294c012de75067adb1a5/href</a></iframe><p>We have one <em>TodoListAdapter</em> variable, which is the one we are going to test and we have an <em>UITableView</em> instance, which we need to <em>mock</em> the <em>UITableView</em> behaviour.</p><p>In our <em>setUp</em> method we will instantiate our <em>UITableView</em> and register an <em>UITableViewCell</em> class for our <em>cellIdentifier</em>. This operations are common to all tests so they can be put in this method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f6c456ee48b169245f6f2edda65ecda/href">https://medium.com/media/3f6c456ee48b169245f6f2edda65ecda/href</a></iframe><p>I also defined a private method to initialise our adapter with different arrays of data. This method is under the <em>fileprivate extension</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25a1eed6c82a07c9c6e7d03ecce46613/href">https://medium.com/media/25a1eed6c82a07c9c6e7d03ecce46613/href</a></iframe><p>We could initialise the adapter with the same data for every test but that would be risky. Why? Let’s take the first test as example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d326a39fb108091bc890b38cd34fcf30/href">https://medium.com/media/d326a39fb108091bc890b38cd34fcf30/href</a></iframe><p>This test initialises the adapter with a data array and asserts that the <em>numberOfRowsInSection</em> returns the correct amount of rows. The <em>tableView’s</em> number of rows should naturally match the count of our data array, testing that when requested, the adapter will provide a correct amount of rows to the <em>tableView</em>.</p><p>Let’s now assume that our <em>numberOfRowsInSection</em> implementation inside our <em>TodoListAdapter</em> is the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/654047df76e0ff8e17ae0c7b2babe994/href">https://medium.com/media/654047df76e0ff8e17ae0c7b2babe994/href</a></iframe><p>If for some reason we defined a fixed return value to our adapter function and we test it against an array (coincidentally) equal in size to our fixed value our test is going to pass even tho our data source implementation isn’t correct. Now if we add a second test with a different data array, one of those tests will fail and we will know that there is something wrong.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d939d51a102f7625c504f78ba72e046/href">https://medium.com/media/4d939d51a102f7625c504f78ba72e046/href</a></iframe><p>Testing with different data sets is always important so we can catch this type of errors. Of course we can’t test every case, but we need to test enough cases to be sure that our code is solid, so we can find bugs and errors quickly and have a more stable codebase. The amount of tests will depend on the logic involved, since we are just loading an array of data, two different cases is more than enough to ensure that the data is correct.</p><p>Last but not least, we are going to test if the data is loaded correctly inside our cells. To avoid a verbose function, I also created a helper function called <em>assertText</em> (which is defined inside the <em>fileprivate</em> extension):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54083f2a398d186067ebc6af895913ba/href">https://medium.com/media/54083f2a398d186067ebc6af895913ba/href</a></iframe><p>As in the previous tests, we initialize our adapter with a data array. After we do that, we retrieve each <em>tableView</em> cell to compare its text against our data array. In this example we test each row manually but we could iterate through the array and calling the helper method for each case to avoid code repetition, and to test big data sets in case the size of the set could break the data source somehow.</p><h3>TodoListViewController</h3><p>After testing our adapter we can move on testing our <em>UIViewController</em>. Since our adapter logic is already tested what we need to test now are the following:</p><ol><li>That our <em>UITableView</em> is connected to our <em>UIViewController</em></li><li>That our <em>accessibility</em> is correct</li></ol><p>In our test class we create an accessibility copy to be able to access our defined labels and instances to the objects that we want to use inside our tests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ef317550d5e0f6497afb53dd92af13e/href">https://medium.com/media/4ef317550d5e0f6497afb53dd92af13e/href</a></iframe><p>Finally, we define our <em>setUp</em> method with the proper initialisations of the data array, the adapter and the <em>UIViewController</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fadaf8abff4e8508df3692516428b94e/href">https://medium.com/media/fadaf8abff4e8508df3692516428b94e/href</a></iframe><p>It is important to highlight a few points about this <em>setUp</em>. The first one is that we are using the <em>convenience init</em> that we created inside our <em>TodoListViewController</em>. The second one is that we are asserting that the controller’s view is not <em>nil</em>. In a future post I will talk more about how to test <em>UIViewControllers</em> but for now you need to know that this assertion is required so the view can be loaded and all the <em>outlets</em> become accessible.</p><p>Once you loaded your view you can test that your assets were loaded properly, in our case the only outlet is the <em>tableView</em>. We also test that our <em>dataSource</em> is properly set:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e67fded8e89d1f3592ded74a7eceb862/href">https://medium.com/media/e67fded8e89d1f3592ded74a7eceb862/href</a></iframe><p>This is important because it can help us to catch errors caused by outlets that were accidentally removed from our <em>xib</em> file, during a refactor or when doing any type of changes to our view. It’s easier to have a test that will let us know that an component was disconnected that to spend hours trying to figure out why the data of our <em>tableView</em> is not loading, even tho “everything is in place”.</p><p>We will also test that our <em>accessibility labels</em> were set properly. By doing this, we can catch UI Test failures in advance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4ae7a2250b624ad8bda584119effdb6/href">https://medium.com/media/e4ae7a2250b624ad8bda584119effdb6/href</a></iframe><h3>Extra</h3><p>Remember our <em>rootViewController</em> setup and how we cared about defining and testing that our <em>accessibility</em> was correct? Well, <em>accessibilityLabels</em> are very useful when doing UI Tests because they help us to locate specific components that we need to test. In this example I create one UI Test to assert if the app is loaded with our <em>TodoListViewController</em> as starting point, after all, it’s useless if our controller’s logic is perfectly tested if it’s not visible to the user right?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2faa751ec2c12cfe2d66eed2353ee316/href">https://medium.com/media/2faa751ec2c12cfe2d66eed2353ee316/href</a></iframe><p>In future posts I will talk more about UI Testing, but for now is enough to say that what we are testing here is if, after the application is launched, the table with the accessibility label that we declared within our <em>TodoListViewController</em> <strong>exists</strong>.</p><h3>Conclusion</h3><p>To have a robust test base is fundamental to develop scalable applications in any platform and to have it is fundamental to be able to test from the smaller components to the more complex ones. <em>Swift protocols</em> give us amazing possibilities to test different components and their integration.</p><p>Even tho the example proposed here is very simple, it is a starting point for those that want to understand how to test <em>Swift</em> base components. In future posts I will explain more deeply how to test another <em>data source</em> methods using more complex view hierarchies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f77a3dc1e90" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>