objective-c XCTAssertEqual 无法比较两个字符串值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19464261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XCTAssertEqual fails to compare two string values?
提问by Konrad77
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 XCTAssertEqualis testing value and not the object itself?
据我所知XCTAssertEqual是测试价值而不是对象本身?
The third line btw, says the string are equal, but XCTAssertEqualsays 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]);
}
回答by Arek Holko
From the documentation of XCTAssertEqual:
从文档XCTAssertEqual:
Generates a failure when a1 is not equal to a2. This test is for C scalars, structs and unions.
当 a1 不等于 a2 时产生失败。此测试适用于 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]);
回答by Leon
I've just had a similar issue which might help someone.
我刚刚遇到了一个类似的问题,可能会对某人有所帮助。
I have a Float extension function which returns a string. The following test fails:
我有一个 Float 扩展函数,它返回一个字符串。以下测试失败:
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.
它通过。
回答by yoAlex5
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]);
}

