سؤال

I'm trying to write unit tests with XCTAssert. I have a NSSet and I want to test if this set holds any objects.

I check with:

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

The test always passes. In my testcase the NSSet is empty. When i insert a if-statement and ask for if (mySet.count == 0) it is true - so they are no elements in the NSSet.

Why is the assert not breaking? Or: How do I check if a NSSet or NSArray is empty with XCTAssert?

هل كانت مفيدة؟

المحلول

The format for the function is

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

The test passes if some condition evaluates to true, and fails if false. Example:

// 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" );

Back to your question:

I want to let the test fail when the NSSet is empty. So the NSSet should always hold data. When count is 0 --> break with an error.

You want to test some items have been added to mySet. There are two tests can use:

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

Also:

In my testcase the NSSet is empty. When i insert a if-statement and ask for if (mySet.count == 0) it is true - so they are no elements in the NSSet

If your set is empty, XCTAssertTrue( mySet.count == 0, @"" ) passes because there no items in mySet.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top