UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Issue with unit testing

Forums > Swift

Hey guys. I am trying to create a unit test for one of my VC.

I would like to test a function within that VC so here is what I wrote:

 func testGetFollowersFunction() {
        // Arrange
        let sut     = FollowersListVC()
        sut.user    = User(login:       "jmgawecki",
                           avatarUrl:   "",
                           name:        "Jakub",
                           location:    "Warsaw",
                           bio:         "Bio",
                           publicRepos: 19,
                           publicGists: 10,
                           htmlUrl:     "",
                           followers:   10,
                           following:   10,
                           createdAt:   "Test")

        // Act
        sut.loadViewIfNeeded()
        sut.getFollowers(page: 1, on: sut.user.login)

        // assert
        XCTAssertEqual(sut.followers.count, 1)   
    }

Function that I am trying to test looks like this:

func getFollowers(page: Int, on username: String) {
        showLoadingView()
        NetworkManager.shared.getFollowers(username: username, page: page) { [weak self] (result) in
            guard let self = self else { return }
            self.dismissLoadingView()

            switch result {
            case .success(let followers):
                if followers.count < 100 { self.hasMoreFollowers.toggle() }
                self.followers.append(contentsOf: followers)
                self.updateData(on: self.followers)
                if self.followers.isEmpty {
                    DispatchQueue.main.async { self.showEmptyStateView(with: "Looks like that user has no followers. Go follow them!", in: self.view) }
                }

            case .failure(let error):
                self.presentGFAlerOnMainThred(title: "Ops", message: error.rawValue, button: "Ok")
            }
        }
    }

That test will not work. XCTAssert will happen before set.getFollowers() will execute. I need to put Expectation and fulfill somewhere in between but I am not sure how to do it. Any suggestions? Thanks!

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.