<?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 Marcos Apóstolo on Medium]]></title>
        <description><![CDATA[Stories by Marcos Apóstolo on Medium]]></description>
        <link>https://medium.com/@marcosapstolo_85088?source=rss-f5c34530e523------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0eKtzu1k6qUqEfRwRRhJDA.jpeg</url>
            <title>Stories by Marcos Apóstolo on Medium</title>
            <link>https://medium.com/@marcosapstolo_85088?source=rss-f5c34530e523------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 18:46:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marcosapstolo_85088/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[Test Driving a TableViewController implementation on iOS]]></title>
            <link>https://medium.com/@marcosapstolo_85088/test-driving-a-tableviewcontroller-implementation-on-ios-ec6c4332eabc?source=rss-f5c34530e523------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec6c4332eabc</guid>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Marcos Apóstolo]]></dc:creator>
            <pubDate>Sat, 04 May 2024 17:13:29 GMT</pubDate>
            <atom:updated>2024-05-04T17:40:17.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m_TxVLkZek5jigP_" /><figcaption>Photo by <a href="https://unsplash.com/@andrewtneel?utm_source=medium&amp;utm_medium=referral">Andrew Neel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Tests are great tools that can prove very useful during software development. They can help you on refactors, help on documenting code and speed up development a lot. In this tutorial I&#39;ll explain how to test drive the implementation of a UITableView on iOS.</p><h4>First Test: Load Items when View Loads</h4><p>Let’s start with a very simple test that guarantees that our List is requesting the load of the items when it loads.</p><p>Since we&#39;ll be test driving our implementation let&#39;s start with a test!</p><pre>import XCTest<br>import UITablewViewTDD<br><br>final class ItemsListUIIntegrationTests: XCTestCase {<br>    func test_onLoad_loadItems() {<br>        let loader = LoaderSpy()<br>        let sut = ItemsListViewController()<br>        <br>        sut.loader = loader<br>        <br>        sut.loadViewIfNeeded()<br>        <br>        XCTAssertEqual(loader.loadMessages.count, 1)<br>    }<br>}</pre><p>First we create a <em>LoaderSpy</em> class that will be explained later, then we create our <strong>System Under Test (sut)</strong><em> </em>that in this case is our<em> ItemsListViewController. </em>Then we use property injection to add our loader to the <em>ItemsListViewController</em>.</p><p>We call <em>loadViewIfNeeded</em> to force our view to load and at the end we check if the number of load calls was one.</p><p>At this moment, this code won&#39;t even be compiling, but that&#39;s <strong>ok </strong>because it&#39;s just the first step. Let&#39;s make it compile.</p><p>First create an empty <em>ItemsListViewController</em></p><pre>import UIKit<br><br>public final class ItemsListViewController: UITableViewController {<br>    <br>}</pre><p>After this let&#39;s create the <em>LoaderSpy</em> class, but before that let&#39;s create the <em>ItemsLoader</em> protocol and <em>Item</em> struct.</p><p>The <em>ItemsLoader</em> protocol will allow us to abstract concrete details from our <em>ItemsListViewController</em>. It could have other benefits in the future, but for now it will allow us to replace the implementation of it with a fake implementation, instead of the real one. After all we don&#39;t want to, for example, be making network requests in such a simple test. This would make our test much slower and susceptible to random failures due to network issues. We could implement later other tests to validate network requests, but for now it&#39;s not our objective.</p><p>The <em>ItemsLoader</em> protocol has only one method called <em>load</em>. It receives a completion handler that receives a <em>Result</em> with an <em>array</em> of <em>Item</em> and an <em>Error </em>and returns<em> Void</em>.</p><p>The <em>Item</em> struct is just a simple model that our list will present.</p><pre>public struct Item {<br>    public let name: String<br><br>    public init(name: String) {<br>        self.name = name<br>    }<br>}<br><br>public protocol ItemsLoader {<br>    func load(completion: @escaping (Result&lt;[Item], Error&gt;) -&gt; Void)<br>}</pre><p>Now we can create our LoaderSpy</p><pre>import XCTest<br>import UITablewViewTDD<br><br>final class ItemsListUIIntegrationTests: XCTestCase {<br>    func test_onLoad_loadItems() {<br>        let loader = LoaderSpy()<br>        let sut = ItemsListViewController()<br>        <br>        sut.loader = loader<br>        <br>        sut.loadViewIfNeeded()<br>        <br>        XCTAssertEqual(loader.loadMessages.count, 1)<br>    }<br>}<br><br>class LoaderSpy: ItemsLoader {<br>    var loadMessages = [(Result&lt;[Item], Error&gt;) -&gt; Void]()<br>    <br>    func load(completion: @escaping (Result&lt;[Item], Error&gt;) -&gt; Void) {<br>        loadMessages.append(completion)<br>    }<br>}</pre><p>For now, our load implementation captures the completion handler into a variable to allow us an easy way to check how many times the load was called. This is important because it has an added bonus of checking not only if the load method was called, but that it was only called <strong>once</strong>.</p><p>Now you&#39;ll at least be able to run the test without build failures. But our test will fail. Again, as expected, because our ItemsListViewController is not doing anything.</p><p>One thing we can do before making our test pass is to take a look at our error message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMYzYcP2YD71hPX_kHen_Q.png" /></figure><p>It is somewhat easy to understand but we can improve that with a third argument to our <em>XCTAssertEqual</em></p><pre>XCTAssertEqual(loader.loadMessages.count, 1, &quot;Expected load to be called once&quot;)</pre><p>Now our error message will look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzZ5kShkFSD3cOEaYxQUvQ.png" /></figure><p>It will help us and other developers to better understand the error in the future if this test ever breaks.</p><p>Now let&#39;s make our test pass:</p><pre>public final class ItemsListViewController: UITableViewController {<br>    public var loader: ItemsLoader?<br>    <br>    public override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        loader?.load(completion: { _ in })<br>    }<br>}</pre><p>Run the test now and it should pass ✅.</p><p>Notice that we pass a completion handler that does nothing. It&#39;s ok since we don&#39;t care about the result for now.</p><h4>Second Test: Displaying an Error Message when the load fails</h4><p>Let&#39;s create a test that displays a message on the view when the load items action fails. There are multiple ways of implementing the actual displaying of the error message, such as using UILabel components or even an Alert. We will use a simple UILabel and what we&#39;ll want to check is if the label is not hidden.</p><p>One important thing is that we won&#39;t test the rendering of this label, for example, making sure that the style is correct and that it is correctly positioned in the screen. The reason is that it&#39;s more recommended to use <strong>snapshot testing</strong> for this objective and we&#39;ll cover this on a later tutorial 📝.</p><p>Here&#39;s our test (or at least the first version of it):</p><pre>  func test_onLoadError_displayErrorMessage() {<br>      let loader = LoaderSpy()<br>      let sut = ItemsListViewController()<br>      <br>      sut.loader = loader<br>      <br>      sut.loadViewIfNeeded()<br><br>      loader.completeWithError()<br>      <br>      XCTAssertFalse(sut.errorMessageLabel.isHidden, &quot;Expect error message to be displayed when load fails&quot;)<br>  }</pre><p>We added the method completeWithError on our LoadeSpy class.</p><pre>class LoaderSpy: ItemsLoader {<br>    var loadMessages = [(Result&lt;[Item], Error&gt;) -&gt; Void]()<br>    <br>    func load(completion: @escaping (Result&lt;[Item], Error&gt;) -&gt; Void) {<br>        loadMessages.append(completion)<br>    }<br>    <br>    func completeWithError(at index: Int = 0) {<br>        loadMessages[index](.failure(anyNSError()))<br>    }<br>}<br><br>func anyNSError() -&gt; Error {<br>    NSError(domain: &quot;any error&quot;, code: 0)<br>}</pre><p>We also created the anyNSError helper method. Sometimes it&#39;s nice to use these methods to avoid code duplication but also as <strong>code as documentation</strong> to inform that in this particular case, any error will suffice, i.e. we don&#39;t care about any specific error.</p><p>Again our code will not be compiling because <em>loadErrorMessage</em> is not defined yet. Let&#39;s create it.</p><pre>  private(set) public lazy var errorMessageLabel: UILabel = {<br>      let label = UILabel()<br>      <br>      label.text = &quot;There was an error when trying to load items&quot;<br>      <br>      return label<br>  }()</pre><p>On our <em>viewDidLoad</em> method let&#39;s add the following code:</p><pre>public override func viewDidLoad() {<br>    super.viewDidLoad()<br>    <br>    loader?.load(completion: { result in<br>        switch result {<br>        case .failure:<br>            self.errorMessageLabel.isHidden = false<br>        default:<br>            break<br>        }<br>    })<br>}</pre><p>We&#39;re just setting the <em>isHidden</em> property of the <em>errorMessageLabel</em> to false when an error occurs. Again, notice how we do not care about the <em>success</em> case, that will come later.</p><p>If you run the test now it will pass ✅.</p><p>But there&#39;s a problem with it. Notice how we never set the initial state of the <em>isHidden</em> property on <em>errorMessageLabel</em> as <em>true </em>when creating it, so our errorMessageLabel was always visible on our view!</p><p>To avoid issues like these it&#39;s always important to do two things:</p><ul><li>Create an habit of always seeing a test failing first and then make it pass ✅</li><li>When appropriate try to add a pre-condition to the test.</li></ul><p>Let&#39;s add an additional assertion to our test to check that the initial state of the isHidden property is true.</p><pre>  func test_onLoadError_displayErrorMessage() {<br>      let loader = LoaderSpy()<br>      let sut = ItemsListViewController()<br>      <br>      sut.loader = loader<br>      <br>      sut.loadViewIfNeeded()<br>      <br>      XCTAssertTrue(sut.errorMessageLabel.isHidden, &quot;Expect error message not to be displayed when view loads&quot;)<br>      <br>      loader.completeWithError()<br>      <br>      XCTAssertFalse(sut.errorMessageLabel.isHidden, &quot;Expect error message to be displayed when load fails&quot;)<br>  }</pre><p>Now the test will break. Let&#39;s make it pass.</p><pre>public final class ItemsListViewController: UITableViewController {<br>    public var loader: ItemsLoader?<br>    <br>    private(set) public lazy var errorMessageLabel: UILabel = {<br>        let label = UILabel()<br>        <br>        label.text = &quot;There was an error when trying to load items&quot;<br>        <br>        // let&#39;s add the initial state here<br>        label.isHidden = true<br>        <br>        return label<br>    }()<br>    <br>    public override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        loader?.load(completion: { result in<br>            switch result {<br>            case .failure:<br>                self.errorMessageLabel.isHidden = false<br>            default:<br>                break<br>            }<br>        })<br>    }<br>}</pre><h4>Refactoring to remove some duplication</h4><p>Tests, like any other code, needs to be maintained. So let&#39;s remove some duplication from our test. The first thing we can do is create a MakeSUT method to create our sut.</p><pre>final class ItemsListUIIntegrationTests: XCTestCase {<br>    func test_onLoad_loadItems() {<br>        let (sut, loader) = makeSUT()<br>        <br>        sut.loadViewIfNeeded()<br>        <br>        XCTAssertEqual(loader.loadMessages.count, 1, &quot;Expected load to be called once&quot;)<br>    }<br>    <br>    func test_onLoadError_displayErrorMessage() {<br>        let (sut, loader) = makeSUT()<br>        <br>        sut.loadViewIfNeeded()<br>        <br>        XCTAssertTrue(sut.errorMessageLabel.isHidden, &quot;Expect error message not to be displayed when view loads&quot;)<br>        <br>        loader.completeWithError()<br>        <br>        XCTAssertFalse(sut.errorMessageLabel.isHidden, &quot;Expect error message to be displayed when load fails&quot;)<br>    }<br>    <br>    // MARK Helpers<br>    func makeSUT() -&gt; (sut: ItemsListViewController, loader: LoaderSpy) {<br>        let loader = LoaderSpy()<br>        let sut = ItemsListViewController()<br>        <br>        sut.loader = loader<br>        <br>        return (sut, loader)<br>    }<br>}</pre><p>Another thing we can do with this setup is to automate memory leak checks by adding the extension:</p><pre>extension XCTestCase {<br>    func checkForMemoryLeaks(_ instance: AnyObject, file: StaticString = #filePath, line: UInt = #line) {<br>        addTeardownBlock { [weak instance] in<br>            XCTAssertNil(instance, file: file, line: line)<br>        }<br>    }<br>}</pre><p>And using it on our <em>makeSUT</em>:</p><pre>  func makeSUT() -&gt; (sut: ItemsListViewController, loader: LoaderSpy) {<br>      let loader = LoaderSpy()<br>      let sut = ItemsListViewController()<br>      <br>      sut.loader = loader<br>      <br>      checkForMemoryLeaks(sut)<br>      checkForMemoryLeaks(loader)<br>      <br>      return (sut, loader)<br>  }</pre><p>Running the tests now we will notice that our tests are failing ❌.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xHW2szTBu9H4nC6IobJrnA.png" /></figure><p>We actually forgot to weakify self on our completion handler. It&#39;s a common mistake that could go unnoticed.</p><p>Let&#39;s fix it:</p><pre>public override func viewDidLoad() {<br>    super.viewDidLoad()<br>    <br>    loader?.load(completion: { [weak self] result in<br>        switch result {<br>        case .failure:<br>            self?.errorMessageLabel.isHidden = false<br>        default:<br>            break<br>        }<br>    })<br>}</pre><p>Now our tests will pass and we&#39;ll be safe from making the same mistake again 🎉.</p><h4>Third Test: Populating our List</h4><p>Let&#39;s create our test:</p><pre>func test_onLoadSuccess_displayItems() {<br>    let (sut, loader) = makeSUT()<br>    <br>    let item0 = Item(name: &quot;a name&quot;)<br>    let item1 = Item(name: &quot;another name&quot;)<br>    let item2 = Item(name: &quot;a different name&quot;)<br>    let allItems = [item0, item1, item2]<br>    <br>    sut.loadViewIfNeeded()<br>    <br>    XCTAssertEqual(sut.numberOfRenderedItemCellViews, 0, &quot;Expected no items load before load items complete&quot;)<br>    <br>    loader.completeSuccessfully(with: allItems)<br>    <br>    XCTAssertEqual(sut.numberOfRenderedItemCellViews, 3, &quot;Expected items displayed when load completes successfully&quot;)<br>    <br>    allItems.enumerated().forEach({ index, item in<br>        let view = sut.itemCell(for: index)<br><br>        guard let itemCell = view as? ItemCell else {<br>            return XCTFail(&quot;Expected \(ItemCell.self) instance, got \(String(describing: view)) instead&quot;)<br>        }<br>        <br>        XCTAssertEqual(itemCell.name, item.name)<br>    })<br>}</pre><p>Here we are checking that the number of rendered cells is equal to the amount of items returned by the loader and that the type of the cells are the <em>ItemCell</em> we will create later and that the property <em>name</em> on each cell is correctly set.</p><p>The implementation of <em>loader.completeSuccessfully</em> is:</p><pre>class LoaderSpy: ItemsLoader {<br>    var loadMessages = [(Result&lt;[Item], Error&gt;) -&gt; Void]()<br>    <br>    func load(completion: @escaping (Result&lt;[Item], Error&gt;) -&gt; Void) {<br>        loadMessages.append(completion)<br>    }<br>    <br>    func completeWithError(at index: Int = 0) {<br>        loadMessages[index](.failure(anyNSError()))<br>    }<br>    <br>    // The implementation here is similar to the method above<br>    func completeSuccessfully(with items: [Item], at index: Int = 0) {<br>        loadMessages[index](.success(items))<br>    }<br>}</pre><p>We also created an extension from our ItemsListViewController with some helpers:</p><pre>extension ItemsListViewController {<br>    var numberOfRenderedItemCellViews: Int {<br>        tableView.numberOfRows(inSection: section)<br>    }<br>    <br>    var section: Int {<br>        0<br>    }<br>    <br>    func itemCell(for index: Int) -&gt; UITableViewCell {<br>        return tableView(tableView, cellForRowAt: IndexPath(row: index, section: section))<br>    }<br>}</pre><p>This test should fail ❌.</p><p>To make it pass, first let&#39;s create a simple <em>ItemCell</em>:</p><pre>public class ItemCell: UITableViewCell {<br>    public var name: String?<br>}</pre><p>Then let&#39;s configure our ItemsListViewController to render the items:</p><pre>public final class ItemsListViewController: UITableViewController {<br>    public var loader: ItemsLoader?<br>    <br>    // First we define our tableModel<br>    var tableModel = [Item]() {<br>        didSet {<br>            self.tableView.reloadData()<br>        }<br>    }<br>    <br>    private(set) public lazy var errorMessageLabel: UILabel = {<br>        let label = UILabel()<br>        <br>        label.text = &quot;There was an error when trying to load items&quot;<br>        <br>        label.isHidden = true<br>        <br>        return label<br>    }()<br>    <br>    public override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        // We register the cells<br>        tableView.register(ItemCell.self, forCellReuseIdentifier: String(describing: ItemCell.self))<br>        <br>        loader?.load(completion: { [weak self] result in<br>            switch result {<br>            case .failure:<br>                self?.errorMessageLabel.isHidden = false<br>            case let .success(items):<br>                // Then we populate our tableModel<br>                self?.tableModel = items<br>            }<br>        })<br>    }<br>    <br>    // Finally we implement the methods to populate the table<br>    public override func numberOfSections(in tableView: UITableView) -&gt; Int {<br>        1<br>    }<br><br>    public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        tableModel.count<br>    }<br>    <br>    public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let identifier = String(describing: ItemCell.self)<br>        <br>        let cell = tableView.dequeueReusableCell(withIdentifier: identifier) as! ItemCell<br>        <br>        let model = tableModel[indexPath.row]<br>        <br>        cell.name = model.name<br>        <br>        return cell<br>    }<br>}</pre><p>Now our tests should be passing ✅.</p><h4>Bonus: Refactoring and Improving our code</h4><p>First let&#39;s improve the assertions on the <em>test_onLoadSuccess_displayItems:</em></p><pre>final class ItemsListUIIntegrationTests: XCTestCase {<br>    func test_onLoad_loadItems() {<br>        let (sut, loader) = makeSUT()<br>        <br>        sut.loadViewIfNeeded()<br>        <br>        XCTAssertEqual(loader.loadMessages.count, 1, &quot;Expected load to be called once&quot;)<br>    }<br>    <br>    func test_onLoadError_displayErrorMessage() {<br>        let (sut, loader) = makeSUT()<br>        <br>        sut.loadViewIfNeeded()<br>        <br>        XCTAssertTrue(sut.errorMessageLabel.isHidden, &quot;Expect error message not to be displayed when view loads&quot;)<br>        <br>        loader.completeWithError()<br>        <br>        XCTAssertFalse(sut.errorMessageLabel.isHidden, &quot;Expect error message to be displayed when load fails&quot;)<br>    }<br>    <br>    func test_onLoadSuccess_displayItems() {<br>        let (sut, loader) = makeSUT()<br>        <br>        let item0 = Item(name: &quot;a name&quot;)<br>        let item1 = Item(name: &quot;another name&quot;)<br>        let item2 = Item(name: &quot;a different name&quot;)<br>        let allItems = [item0, item1, item2]<br>        <br>        sut.loadViewIfNeeded()<br>        <br>        assertThat(sut, isRendering: [])<br>        <br>        loader.completeSuccessfully(with: allItems)<br>        <br>        assertThat(sut, isRendering: allItems)<br>    }<br>    <br>    // MARK Helpers<br>    func makeSUT(file: StaticString = #filePath, line: UInt = #line) -&gt; (sut: ItemsListViewController, loader: LoaderSpy) {<br>        let loader = LoaderSpy()<br>        let sut = ItemsListViewController()<br>        <br>        sut.loader = loader<br>        <br>        checkForMemoryLeaks(sut, file: file, line: line)<br>        checkForMemoryLeaks(loader, file: file, line: line)<br>        <br>        return (sut, loader)<br>    }<br>    <br>    // We use this helper method to make the same assertions we had before<br>    func assertThat(_ sut: ItemsListViewController, isRendering items: [Item], file: StaticString = #filePath, line: UInt = #line) {<br>        XCTAssertEqual(sut.numberOfRenderedItemCellViews, items.count, &quot;Expected items displayed when load completes successfully&quot;)<br>        <br>        items.enumerated().forEach({ index, item in<br>            let view = sut.itemCell(for: index)<br><br>            guard let itemCell = view as? ItemCell else {<br>                return XCTFail(&quot;Expected \(ItemCell.self) instance, got \(String(describing: view)) instead&quot;)<br>            }<br>            <br>            XCTAssertEqual(itemCell.name, item.name)<br>        })<br>    }<br>}</pre><p>Notice how the test is easier to read now!</p><p>Finally if we look at our <em>ItemsListViewController</em> it&#39;s already starting to get big and full of responsibilities like handling presentation and handling the result of the load request. These responsibilities could be moved to a <em>ItemsListViewModel.</em></p><pre>public class ItemsListViewModel {<br>    private let loader: ItemsLoader<br>    <br>    typealias Observer&lt;T&gt; = (T) -&gt; Void<br>    <br>    var onErrorStateChange: Observer&lt;Void&gt;?<br>    var onItemsLoad: Observer&lt;[Item]&gt;?<br>    <br>    public init(loader: ItemsLoader) {<br>        self.loader = loader<br>    }<br>    <br>    public let errorMessage = &quot;There was an error when trying to load items&quot;<br>    <br>    func loadItems() {<br>        loader.load(completion: { [weak self] result in<br>            switch result {<br>            case .failure:<br>                self?.onErrorStateChange?(())<br>            case let .success(items):<br>                self?.onItemsLoad?(items)<br>            }<br>        })<br>    }<br>}</pre><p>And our ItemsListViewController will look like this:</p><pre>public final class ItemsListViewController: UITableViewController {<br>    // We removed the loader from the ItemsListViewController since it&#39;s not needed anymore<br>    public var viewModel: ItemsListViewModel? {<br>        <br>        didSet { <br>          bind() <br>        }<br>    }<br>    <br>    var tableModel = [Item]() {<br>        didSet {<br>            self.tableView.reloadData()<br>        }<br>    }<br>    <br>    private(set) public lazy var errorMessageLabel: UILabel = {<br>        let label = UILabel()<br>        <br>        // The error message now comes from the viewModel<br>        label.text = viewModel?.errorMessage<br>        <br>        label.isHidden = true<br>        <br>        return label<br>    }()<br>    <br>    public override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        tableView.register(ItemCell.self, forCellReuseIdentifier: String(describing: ItemCell.self))<br>        <br>        // We call loadItems from the viewModel instead of directly from the loader<br>        viewModel?.loadItems()<br>    }<br>    <br>    func bind() {<br>        // Now the ItemsListViewController is notified when an error or sucess happens<br>        viewModel?.onErrorStateChange = { [weak self] _ in<br>            self?.errorMessageLabel.isHidden = false<br>        }<br>        viewModel?.onItemsLoad = { [weak self] items in<br>            self?.tableModel = items<br>        }<br>    }<br>    <br>    public override func numberOfSections(in tableView: UITableView) -&gt; Int {<br>        1<br>    }<br>    <br>    public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        tableModel.count<br>    }<br>    <br>    public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let identifier = String(describing: ItemCell.self)<br>        <br>        let cell = tableView.dequeueReusableCell(withIdentifier: identifier) as! ItemCell<br>        <br>        let model = tableModel[indexPath.row]<br>        <br>        cell.name = model.name<br>        <br>        return cell<br>    }<br>}</pre><p>On our tests we only have to make changes to the makeSUT:</p><pre>func makeSUT(file: StaticString = #filePath, line: UInt = #line) -&gt; (sut: ItemsListViewController, loader: LoaderSpy) {<br>    let loader = LoaderSpy()<br>    let sut = ItemsListViewController()<br>    // Loader now is passed to the ItemsListViewModel<br>    let viewModel = ItemsListViewModel(loader: loader)<br>    <br>    // We need to set the viewModel on ItemsListViewController<br>    sut.viewModel = viewModel<br>    <br>    checkForMemoryLeaks(sut, file: file, line: line)<br>    checkForMemoryLeaks(loader, file: file, line: line)<br>    <br>    return (sut, loader)<br>}</pre><p>Run the tests and they are passing 🎉!</p><p>Notice how we didn&#39;t have to change anything on our tests to after this refactoring. On the opposite, they guided us on the refactor and made us sure that we didn&#39;t break anything on the process.</p><p>Since the setup on makeSUT is getting messy let&#39;s create a composer class to make it easier to create our ItemsListViewController</p><pre>public class ItemsListUIComposer {<br>    private init() {}<br>    <br>    public static func makeItemsList(loader: ItemsLoader) -&gt; ItemsListViewController {<br>        let vc = ItemsListViewController()<br>        let viewModel = ItemsListViewModel(loader: loader)<br>        <br>        vc.viewModel = viewModel<br>        <br>        return vc<br>    }<br>}</pre><p>Now the tests don&#39;t need to know about how the ItemsListViewController is composed which adds much more flexibility:</p><pre>func makeSUT(file: StaticString = #filePath, line: UInt = #line) -&gt; (sut: ItemsListViewController, loader: LoaderSpy) {<br>    let loader = LoaderSpy()<br>    let sut = ItemsListUIComposer.makeItemsList(loader: loader)<br>    <br>    checkForMemoryLeaks(sut, file: file, line: line)<br>    checkForMemoryLeaks(loader, file: file, line: line)<br>    <br>    return (sut, loader)<br>}</pre><h4>Bonus #2: Threading test</h4><p>There&#39;s an issue with our implementation. Since our load method is async it will complete in a background thread and with that we would be updating the tableView on a background thread. The result would be a crash 🔥. Let&#39;s add a test to confirm that:</p><pre>func test_loadItems_dispatchesFromBackgroundToMainThread() {<br>    let (sut, loader) = makeSUT()<br>    <br>    sut.loadViewIfNeeded()<br><br>    let exp = expectation(description: &quot;Wait for background queue&quot;)<br>    <br>    DispatchQueue.global().async {<br>        // We don&#39;t care about the items here. It just need to complete.<br>        loader.completeSuccessfully(with: [])<br>        exp.fulfill()<br>    }<br>    <br>    wait(for: [exp], timeout: 1.0)<br>}</pre><p>The result is a failing test and we can see this message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*3l1sy8X1D9dMUpcM2mTaSA.png" /></figure><p>To make this test pass we could add dispatch commands all over our ItemsListViewController but we can also use a decorator for our loader, with the added bonus that we use our new composer to help us:</p><pre>public class ItemsListUIComposer {<br>    private init() {}<br>    <br>    public static func makeItemsList(loader: ItemsLoader) -&gt; ItemsListViewController {<br>        let vc = ItemsListViewController()<br>        let viewModel = ItemsListViewModel(loader: DispatchOnMainQueueDecorator(decoratee: loader))<br>        <br>        vc.viewModel = viewModel<br>        <br>        return vc<br>    }<br>}<br><br>class DispatchOnMainQueueDecorator: ItemsLoader {<br>    private let decoratee: ItemsLoader<br>    <br>    init(decoratee: ItemsLoader) {<br>        self.decoratee = decoratee<br>    }<br>    <br>    func load(completion: @escaping (Result&lt;[Item], Error&gt;) -&gt; Void) {<br>        decoratee.load { result in<br>            if Thread.isMainThread {<br>                completion(result)<br>            } else {<br>                DispatchQueue.main.async {<br>                    completion(result)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Now our tests are passing ✅!</p><p>Depending on the behaviors of out list we could be implemented other tests, such as adding tests to check loading states, behavior for when a cell will be displayed, etc.</p><p>You can check the final version on <a href="https://github.com/MarcosApostolo/UITableViewTDD">github</a>.</p><h4>References</h4><ul><li><a href="https://www.essentialdeveloper.com/">https://www.essentialdeveloper.com/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec6c4332eabc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>