简体   繁体   English

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

[英]Compare Strings in Swift unit test

How do you test whether two Strings are equal in a Swift unit test?如何在 Swift 单元测试中测试两个字符串是否相等? I've tried the == operator but it doesn't recognize it:我试过==运算符,但它无法识别:

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.
    }
}

}

And the actual method being tested from MyProject.swift:从 MyProject.swift 测试的实际方法:

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

This part:这部分:

XCTAssertTrue(json == "")

Throws:抛出:

Operator is not a known binary operator

The problem is that toJSONTest is not a test.问题是toJSONTest不是测试。 Change the name to testToJSON .将名称更改为testToJSON

This works fine on my machine:这在我的机器上运行良好:

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

The test runs, and passes.测试运行,并通过。 However, I would probably write it like this:但是,我可能会这样写:

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

Although this question is explicitly about how to compare two Strings in a Swift unit test, what's implicit in the question is how to compare two JSON Strings.虽然这个问题明确是关于如何在 Swift 单元测试中比较两个字符串,但问题中隐含的是如何比较两个 JSON 字符串。 I just wanted to point out that the right thing to do when comparing two JSON strings is to parse the JSON Strings to a Foundation object with the JSONSerialization class and then to compare the resulting Foundation objects.我只是想指出,在比较两个 JSON 字符串时,正确的做法是使用JSONSerialization类将 JSON 字符串解析为 Foundation 对象,然后比较生成的 Foundation 对象。 This approach takes care of the problem of the two JSON Strings having slightly different formatting or fields in a different order.这种方法可以解决两个 JSON 字符串格式稍有不同或字段顺序不同的问题。 So, for example, it's important that "{\\"a\\":1,\\"b\\":2}" and "{\\"b\\":2,\\"a\\":1}" are deemed to be equal because they are logically equal.因此,例如,重要的是"{\\"a\\":1,\\"b\\":2}""{\\"b\\":2,\\"a\\":1}"被视为是相等的,因为它们在逻辑上是相等的。

Here's a Swift function I put together which helps with this comparison:这是我放在一起的一个 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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM