NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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!

1      

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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.