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

3

在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 == "")

抛出错误:

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


1
请展示完整的单元测试文件。 - matt
2个回答

5
问题在于 toJSONTest 不是一个测试。请将其更名为 testToJSON
在我的电脑上运行正常:
func testToJSON() {
    let json = ""
    XCTAssertTrue(json == "")
}

测试运行并通过。但我可能会将其写成这样:
func testToJSON() {
    let json = ""
    XCTAssertEqual(json, "", "They are not equal")
}

此外,请注意您的测试(如果它是一个测试),从未调用 func toJSON,因此实际上并没有测试任何内容。 - matt
那时我改变了它,以找出如何比较字符串。它仍然会抛出相同的错误,名称为testToJSON()。 - JBaczuk
我的机器上运行良好。 - matt
我使用的是 XCode 版本 7.1 beta 3 (7B85),如果有所影响请知悉。 - JBaczuk
1
你为什么在使用 beta 版本?7.1 已经发布正式版一段时间了。我不认为这很重要,但这是一个愚蠢的做法。 - matt

5
虽然这个问题明确是关于如何在Swift单元测试中比较两个字符串,但问题中隐含的是如何比较两个JSON字符串。我想指出的是,当比较两个JSON字符串时,正确的做法是将JSON字符串解析为Foundation对象,使用JSONSerialization类,然后比较生成的Foundation对象。这种方法可以解决两个JSON字符串具有稍微不同的格式或字段顺序的问题。例如,重要的是要认为"{\"a\":1,\"b\":2}""{\"b\":2,\"a\":1}"是相等的,因为它们在逻辑上是相等的。
下面是我整理的一个Swift函数,可以帮助进行这种比较:
class JSONAssert {

    class func assertEquals(expected: String, actual: String) {
    
        let expectedData = Data(expected.utf8)
        let actualData = Data(actual.utf8)
    
        let expectedObject: Any
        let actualObject: Any
    
        do {
            expectedObject = try JSONSerialization.jsonObject(with: expectedData, options: [])
        } catch {
            XCTFail("Failed constructing a Foundation object from `expected` (i.e. \(expected)): \(error)")
            return
        }
    
        do {
            actualObject = try JSONSerialization.jsonObject(with: actualData, options: [])
        } catch {
            XCTFail("Failed constructing a Foundation object from `actual` (i.e. \(actual)): \(error)")
            return
        }
    
        guard let expectedDictionary = expectedObject as? NSDictionary else {
            XCTFail("Failed casting expected object (i.e. \(expectedObject)) to an NSDictionary")
            return
        }
    
        guard let actualDictionary = actualObject as? NSDictionary else {
            XCTFail("Failed casting actual object (i.e. \(actualObject)) to an NSDictionary")
            return
        }
    
        XCTAssertEqual(expectedDictionary, actualDictionary)
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接