Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Testing for XCTAssertThrows in Swift
class ExceptionTestCase: XCTestCase {
func raisesException() {
var exception = NSException(name: NSInternalInconsistencyException, reason: "Testing exceptions", userInfo: nil)
XCTAssertThrows({ exception.raise() }, "Should raise an exception)
XCTAssertThrowsSpecific({ exception.raise() }, NSInternalInconsistencyException, "Should raise NSInternalInconsistencyException")
}
}
#import "XCTestCase+Exceptions.h"
@import Foundation;
@import XCTest;
@interface XCTestCase (Exceptions)
- (void)XCTAssertThrows:(void (^)(void))block :(NSString *)message;
- (void)XCTAssertThrowsSpecific:(void (^)(void))block :(NSString *)name :(NSString *)message;
@end
#import "XCTestCase+Exceptions.h"
@implementation XCTestCase (Exceptions)
- (void)XCTAssertThrows:(void (^)(void))block :(NSString *)message {
XCTAssertThrows(block(), @"%@", message);
}
- (void)XCTAssertThrowsSpecific:(void (^)(void))block :(NSString *)exceptionName :(NSString *)message {
BOOL __didThrow = NO;
@try {
block();
}
@catch (NSException *exception) {
__didThrow = YES;
XCTAssertEqualObjects(exception.name, exceptionName, @"%@", message);
}
@catch (...) {
__didThrow = YES;
XCTFail(@"%@", message);
}
if (!__didThrow) {
XCTFail(@"%@", message);
}
}
@end
@e28eta

This comment has been minimized.

Copy link

commented Dec 18, 2014

Thanks. I ran into a problem when my block in Swift doesn't have a return value of Void (to match the Obj-C definition).

In particular: my block had a single expression whose type was "String!", and I was getting "error: 'String!' is not a subtype of 'Void'"

It was quickly solved by changing the return type of the block to 'id', but then it's incompatible with blocks that don't return anything. I haven't needed to go any farther, so I'm not sure what the best solution is.

@francocarbonaro

This comment has been minimized.

Copy link

commented Jan 17, 2015

Thanks. I got a little confused with the example that was shown, to use your solution I had to code something like this:

func testSomething () {
    var exception = NSException(
        name: NSInvalidArgumentException,
        reason: "some reason",
        userInfo: nil
    )

    XCTAssertThrowsSpecific(
        {
            var object =  Object ()
        },
        NSInvalidArgumentException,
        "some message"
    )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.