Swift中的单元测试

时间:2017-12-19 12:01:29

标签: swift unit-testing

我正在快速学习单元测试,我想知道我是否正确行事。

这里有模型

struct ChangePasswordRequest: Encodable {
    var email: String
    var newPassword: String
    var token: String
}

这里是单元测试

import XCTest
@testable import MyProject

class ChangePasswordRequestTests: XCTestCase {

    var changePasswordRequest: ChangePasswordRequest!

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        changePasswordRequest = nil
        super.tearDown()
    }

    func testChangePasswordRequest() {

        // given
        let email = "abc@def.com.br"
        let newPassword = "abc123"
        let token =
        """
        rF1rHbYVCpcfyo6K2e7Q68QvKYdeOMt0vDXYehggGU3kx8XiuGmQylXabxbGAyUmSK9RnbL
        """

        // when
        changePasswordRequest = ChangePasswordRequest(email: email, newPassword: newPassword, token: token)

        let requestJSON = """
        {"email":"\(email)","token":"\(token)","newPassword":"\(newPassword)"}
        """

        changePasswordRequest = ChangePasswordRequest(email: email, newPassword: newPassword, token: token)
        guard let encodedRequest = try? JSONEncoder().encode(changePasswordRequest) else {
            XCTFail()
            return
        }

        // then
        XCTAssertEqual(String(data: encodedRequest, encoding: .utf8)!, requestJSON, "Any JSON key differs from model.")

    }

}

我从未参与过单元测试。有可能改进这项测试吗?

0 个答案:

没有答案