I am setting up unit tests to run methods that should generate an NSError. For some reason, I can’t get to the NSError from the unit tests. I created a sample method to test this, and it still doesn’t work. What am I doing wrong?
Implementation file:
- (BOOL)createAnError:(NSError **)error {
NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary];
[errorDetail setValue:NSLocalizedString(@"This error should be testable", @"")
forKey:NSLocalizedDescriptionKey];
[errorDetail setObject:self
forKey:NSValidationObjectErrorKey];
NSError *cannotDeleteError = [NSError errorWithDomain:@"myErrorDomain"
code:12345
userInfo:errorDetail];
if (*error = nil)
*error = cannotDeleteError;
return NO;
}
Unit Test:
- (void)testNSErrors {
Unit *myObj = [NSEntityDescription insertNewObjectForEntityForName:@"TestObject"
inManagedObjectContext:managedObjectContext];
NSError *error = nil;
STAssertFalse([myObj createAnError:&error], @"This method should return NO");
STAssertEquals([error code], 12345, @"The error code is incorrect. (error = %@)", error);
}
The error I’m seeing in the build results is: error: -[LogicTests testNSErrors] : '0' should be equal to '12345': The error code is incorrect. (error = (null)).
So why is this happening? Am I creating the NSError incorrectly, testing for it incorrectly, or both?
Thank you!
You are not creating the error correctly. In your sample method, you test for
if (*error = nil). This is an assignment. What you really mean to say is:if (*error == nil), which uses the equality operator.Change that and you should get a positive result.