Search code examples
objective-cunit-testingxctest

Expect assert when using XCTest


I'm using XCTest in an Objective C project.

In my unit test target function, I use NSAssert to exit when receive an exception.

Even this behavior is expected, the XCTest still treat it as a failure.

Is there a way for XCTest to mark that this unit test is expected to assert?


Solution

  • You use XCAssertThrow macro to test for an arbitrary exception of an expression:

    - (void)method {
        @throw [[NSException alloc] initWithName:@"My Exception" reason:nil userInfo:nil];
    }
    
    - (void)testThrows {
        XCTAssertThrows([self method], @"The method must throw");
    }