string - 在 Swift 单元测试中比较字符串

标签 string swift unit-testing

如何在 Swift 单元测试中测试两个字符串是否相等?我试过 == 运算符,但它无法识别它:

import XCTest
@testable import MyProject

class MyProject: XCTestCase {

override func setUp() {
    super.setUp()
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

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

func testExample() {
    // This is an example of a functional test case.
    // Use XCTAssert and related functions to verify your tests produce the correct results.
    XCTAssertNil(nil, "This test works")
}

func toJSONTest() {
    let currentLocation = deviceLocation(timestamp: "2015-11-02 16:32:15 +0000",latitude: "40.2736577695212",longitude: "-111.715408331498")
    var MyProjectStatuses = [MyProjectStatus(id: "", currentLocation: currentLocation)]
    let json = ""
    XCTAssertTrue(json == "")
}

func testPerformanceExample() {
    // This is an example of a performance test case.
    self.measureBlock {
        // Put the code you want to measure the time of here.
    }
}

}

以及从 MyProject.swift 测试的实际方法:

func toJSON ()->String{
    var json = ""
    json = "{\"myproject_status\":"
    json = json + "{\"id\":\"" + self.Id + "\""
    return json 
}

这部分:

XCTAssertTrue(json == "")

抛出:

运算符不是已知的二元运算符

最佳答案

问题是 toJSONTest 不是测试。将名称更改为 testToJSON

这在我的机器上运行良好:

func testToJSON() {
    let json = ""
    XCTAssertTrue(json == "")
}

测试运行并通过。但是,我可能会这样写:

func testToJSON() {
    let json = ""
    XCTAssertEqual(json, "", "They are not equal")
}

关于string - 在 Swift 单元测试中比较字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33483481/

相关文章:

c++ - 我们可以从 char 指针创建一个 C++ 字符串对象,其中对字符串对象的操作反射(reflect)到源 char 指针吗?

c++ - 以编程方式在 C++ 中获取转义字符串表示

python - 让 Nose 忽略名称中带有 'test' 的函数

android - 在 `runBlockingTest` 测试 Room 的事务查询

ruby - 如果字符串以该字符开头,则从字符串中删除该字符?

MySQL复杂字符串匹配

ios - 直方图如何针对 vImageHistogramCalculation_Planar8 中的不同 channel 工作

ios - 快速更改计算属性

Swift 3.0 使用 Segue 在 View Controller 之间传递信息

unit-testing - 使用 Agent 串行运行 ExUnit.Case 函数