Search code examples
objective-cocunit

STAssertTrue not returning as I expect


I'm just starting OCUnitTesting. I don't think that my code is wrong, but the problem is probably is a tiny mistake I made somewhere along the way.. I have a function

- (BOOL)tooManyCouplesForER:(NSMutableArray *)startfield
{
    NSLog(@"Size %i", [startfield count]);
    if ([startfield count] > 7) {
        return true;
    } else{
        return false;
    }
}

inside my ViewController StartfieldTableViewController.

I included UnitTests to my project and in AppTests.h I did

#import "StartfieldTableViewController.h"

and

@property (strong, nonatomic) StartfieldTableViewController *start;

In the AppTests.m I wrote a test

- (void)testTooManyCouplesForER
{
    NSMutableArray *testField = [[NSMutableArray alloc] initWithObjects:@"1", @"1", @"1", @"1", @"1", @"1", @"1", @"1", @"1", @"1", nil];
    BOOL sum = [self.start tooManyCouplesForER:testField];

    NSLog(@"BOOL = %@\n", (sum ? @"YES" : @"NO"));
    STAssertTrue(sum, @"This should have returned true, but it returned false");
}

So I would expect the test to pass, as I gave it an array with 10 elements. It fails. So I made the NSLog, and it really is NO in the test, but testing the function in runtime, with the very same testField-array, it is true.

Thanks for helping.


Solution

  • In the unit test, check before you execute

      BOOL sum = [self.start tooManyCouplesForER:testField];
    

    that self.start is not nil.

      STAssertNotNil(self.start,@"You forgot to set the controller")
      BOOL sum = [self.start tooManyCouplesForER:testField];
    

    I bet it's not being initialized in the unit test, so sum is nil, and the test fails.