【问题标题】:XCTAssert NSSet countXCTAssert NSSet 计数
【发布时间】:2014-02-11 19:59:17
【问题描述】:

我正在尝试使用 XCTAssert 编写单元测试。 我有一个 NSSet,我想测试这个集合是否包含任何对象。

我检查:

XCTAssertTrue((mySet.count == 0), @"mySet should not be empty");

测试总是通过。在我的测试用例中,NSSet 是空的。当我插入一个 if 语句并要求 if (mySet.count == 0) 时,这是真的 - 所以它们不是 NSSet 中的元素。

为什么断言没有中断? 或者:如何使用 XCTAssert 检查 NSSet 或 NSArray 是否为空?

【问题讨论】:

  • 你是如何创建集合的,此时它应该是空的吗?您传入的字符串与实际测试相矛盾。
  • NSSet 是来自 NSManagedObject 的关系。当 NSSet 为空时,我想让测试失败。所以 NSSet 应该总是保存数据。当 count 为 0 时 --> 出现错误。

标签: ios unit-testing xctest


【解决方案1】:

函数的格式是

XCTAssertTrue( <some condition>, @"Some string that gets printed to the console if the test fails" )

如果 某个条件 评估为真,则测试通过,如果为假,则测试失败。示例:

// create empty set
NSSet *mySet = [[NSSet alloc] init];
// this test passes because the set is empty
XCTAssertTrue( [mySet count] == 0, @"Set should be empty" );

// Set with three items
NSSet *setTwo = [[NSSet alloc] initWithArray:@[ @"1", @"2", @"3" ]];
// passes test because there are three items
XCTAssertTrue( [setTwo count] == 3, @"We should have three items" );
// failing test
XCTAssertTrue( [setTwo count] == 0, @"This gets printed to the console" );

回到你的问题:

我想让测试在 NSSet 为空时失败。所以NSSet 应始终保存数据。当 count 为 0 时 --> 出现错误。

您要测试的一些项目已添加到mySet。有两种测试可以使用:

XCTAssertTrue( [mySet count] > 0, @"Should have at least one item" );
// or
XCTAssertFalse( [mySet count] == 0, @"mySet count is actually %d", [mySet count] );

还有:

在我的测试用例中,NSSet 是空的。当我插入一个 if 语句和 询问 if (mySet.count == 0) 是否为真 - 所以它们不是 NSSet

如果您的集合为空,XCTAssertTrue( mySet.count == 0, @"" ) 将通过,因为mySet 中没有项目。

【讨论】:

    猜你喜欢
    • 2011-08-24
    • 2015-10-28
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 2014-10-07
    相关资源
    最近更新 更多