简体   繁体   English

XCTAssertEqual 无法比较两个字符串值?

[英]XCTAssertEqual fails to compare two string values?

I added a simple unit test to test my string extension.我添加了一个简单的单元测试来测试我的字符串扩展。 But it fails.但它失败了。 What I am I doing wrong here?我在这里做错了什么?

From what I know XCTAssertEqual is testing value and not the object itself?据我所知XCTAssertEqual正在测试价值而不是对象本身?

The third line btw, says the string are equal, but XCTAssertEqual says they're not.顺便说一句,第三行表示字符串相等,但XCTAssertEqual表示它们不是。

- (void) testInitialsFromFullname {
    NSString *firstNickName = @"Mike Kain";
    NSString *expectedResult = @"MK";
    NSLog(@"Equal:%@", [[firstNickName initialsFromString] isEqualToString:expectedResult] ? @"YES" : @"NO");

    XCTAssertEqual(expectedResult, [firstNickName initialsFromString], @"Strings are not equal %@ %@", expectedResult, [firstNickName initialsFromString]);
}

From the documentation of XCTAssertEqual :XCTAssertEqual的文档中:

Generates a failure when a1 is not equal to a2.当 a1 不等于 a2 时产生失败。 This test is for C scalars, structs and unions.此测试适用于 C 标量、结构和联合。

You should use XCTAssertEqualObjects (which uses isEqual: internally) or something like:您应该使用XCTAssertEqualObjects (它在内部使用isEqual: )或类似的东西:

XCTAssertTrue([[firstNickName initialsFromString] isEqualToString:expectedResult],
              @"Strings are not equal %@ %@", expectedResult, [firstNickName initialsFromString]);

I've just had a similar issue which might help someone.我刚刚遇到了一个类似的问题,可能会对某人有所帮助。

I have a Float extension function which returns a string.我有一个 Float 扩展函数,它返回一个字符串。 The following test fails:以下测试失败:

testValue = 0.01
XCTAssertEqual(testValue.formattedForCost(), "0,01 €")

With the following message:带有以下消息:

Assertions: XCTAssertEqual failed: ("Optional("0,01 €")") is not equal to ("Optional("0,01 €")")

Which is rather annoying.这是相当烦人的。 However I discovered if I change my test to use the unicode no-break space character :但是我发现如果我将测试更改为使用unicode 不间断空格字符

XCTAssertEqual(testValue.formattedForCost(), "0,01\u{00a0}€")

It passes.它通过。

Comparing strings比较字符串

- (void) testStringComparison {

    NSString *first = @"my string";
    NSString *second = @"my string";

    NSMutableString *firstMutable = [NSMutableString stringWithString:first];

    //== comparing addresses of the objects(pointer comparison)
    //`first` and `second` has the same address it is a compiler optimization to store only one copy
    XCTAssertTrue(first == second);
    XCTAssertFalse(first == firstMutable);

    XCTAssertEqual(first, second);
    XCTAssertNotEqual(first, firstMutable);
    XCTAssertEqualObjects(first, firstMutable);
    XCTAssertTrue([first isEqualToString:firstMutable]);
}

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

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