Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing unit tests for a Moya request

Tags:

testing

moya

I want to start writing test cases for all my Moya requests. How can I test a simple Moya .get request generated from Swift?

like image 496
dhamini poornachandra Avatar asked Jun 09 '17 09:06

dhamini poornachandra


1 Answers

This is how I am doing my unit tests with Moya. I have my NetworkManager which makes all the requests and the init with a default parameter (to use it on production code) so we can specify a different provider when testing.

class NetworkManager {
    private let provider: MoyaProvider<MultiTarget>

    init(provider: MoyaProvider<MultiTarget> = MoyaProvider<MultiTarget>()) {
        self.provider = provider
    }

    func createUser(_ user: User, completion: @escaping (Result<User>) -> Void) {
        provider.request(MultiTarget(UserApi.createUser(user: user))) { (result) in
            switch result {
            case .success(let response):
                do {
                    let user = try response.map(User.self)
                    completion(.success(user))
                } catch let error {
                    completion(.error(error))
                }
            case .failure(let error):
                completion(.error(error))
            }
        }
    }

    // other requests...
}

So on production code you can have something like this:

let manager = NetworkManager()
let viewController = ViewController(networkManager: manager)

And on testing something like:

class TestMoyaTests: XCTestCase {    
    var networkManager: NetworkManager!

    override func setUp() {
        super.setUp()
        networkManager = NetworkManager(provider: MoyaProvider<MultiTarget>(stubClosure: MoyaProvider.immediatelyStub))
    }

    func testGetUser() {
        let expected = User(id: "1", name: "John")
        var response: User?
        networkManager.getUser(id: "1") { (result) in
            if case let .success(user) = result {
                response = user
            }
        }
        XCTAssert(response == expected)
    }
    
    // other tests...
}

Or if what you are looking is to test the MoyaProvider itself, you can check how Moya's team doing it. Since the stubs are returned immediately, there is no need of expections or something like that (that is how Moya's team test .sampleData).

Hope this helps!

like image 171
rgkobashi Avatar answered Nov 15 '22 03:11

rgkobashi