views:

70

answers:

1

Hallo,

I am trying to set up some unit tests for code that accepts an *NSError as an argument. If there is a validation problem, then the object is not saved and the NSError condition is set.

My method is:

- (BOOL)validateConsistency:(NSError **)error {

    ... code omitted for brevity ...

    if (errorCondition == YES) {
        NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary];
        [errorDetail setValue:@"Validation failed " forKey:NSLocalizedDescriptionKey];
        *error = [NSError errorWithDomain:@"myDomain" code:100 userInfo:errorDetail];
        return nil;
    }
    ...
}

Once I've created the conditions that should generate this error, how can I STAssert/test for it in my unit tests?

Thanks.

+3  A: 

You're doing this slightly wrong in two places:

  • You're returning nil when you mean to return NO
  • You're not checking error != nil before assigning to it. It is legal to pass nil as your NSError pointer to mean "I don't care."

Once you fix those, you can test the working case with

STAssertTrue(validateConsistency:nil, ...)

For error conditions, you'd just do it this way:

NSError *error;
STAssertFalse(validateConsistency:&error, ...); // Make sure we failed
STAssertEqual([error code], 100, ...); // Make sure the code is right; we can assume the domain is right, or you could check it.
Rob Napier