使用RxSwift中的Stub提供程序进行signUp验证的XcTest案例

时间:2017-11-09 07:14:53

标签: ios swift rx-swift xctestcase

我是新手使用嘲弄存根你能帮助任何人!!

每次收到像XCTAssertEqual一样的错误时进行signUp测试失败:(“201”)不等于(“200”)。

  • 如何在不使用后端数据的情况下测试硬编码signUp详细信息

  • 如何测试状态代码对成功和失败的响应

应该感谢任何帮助 - 谢谢你

class LoginServiceUnitTests: XCTestCase {
    var stubProvider = RxMoyaProvider<RestApi>()
    override func setUp() {
        super.setUp()
        stubProvider = RxMoyaProvider<RestApi>(stubClosure: MoyaProvider.immediatelyStub)
    }

    func testSignUpForSuccessResponse() {

        let userData = Creator()
        userData?.username = "raj@naresh.com"
        userData?.password = "password"
        userData?.displayName = "username"
        let target: RestApi = .signUp(userData!)
        stubProvider.request(target) { result in
            if case let .success(response) = result {
                XCTAssertEqual("201", String(response.statusCode))

            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

extension XCTest {

    func customStatusCodeEndPoint(_ target: (RestApi), statusCode: Int) -> Endpoint<RestApi> {
        let url = target.baseURL.appendingPathComponent(target.path).absoluteString
        return Endpoint(url: url, sampleResponseClosure: {.networkResponse(statusCode, target.sampleData)}, method: target.method, parameters: target.parameters, parameterEncoding: target.parameterEncoding)
    }
}

使用端点闭包在您的测试用例中写入,如下所示

func testSignUpURLRequestForStubbedData(){

    let endpointClosure = { (target: RestApi) -> Endpoint<RestApi> in
        self.customStatusCodeEndPoint(target, statusCode: 201)
    }
    stubProvider = RxMoyaProvider<RestApi>(endpointClosure: endpointClosure, stubClosure: RxMoyaProvider.immediatelyStub)
    let userData = Creator()!
    userData.username = "raj@naresh.com"
    userData.password = "password"
    userData.displayName = "Surya"
    let target: RestApi = .signUp(userData)
    stubProvider.request(target) { result in
        if case .success(let response) = result {
            log.debug(response.statusCode)
            XCTAssertEqual("201", String(response.statusCode))

        }
    }
}