Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bridging XCTAssertThrows to Swift to catch exceptions. (Doesn't work with assert(), though)
class ExceptionTestCase: XCTestCase {
func raisesException() {
var exception = NSException(name: NSInternalInconsistencyException, reason: "Testing exceptions", userInfo: nil)
XCTAssertThrows({ exception.raise() })
XCTAssertThrowsSpecific({ exception.raise() }, NSInternalInconsistencyException, "Should raise NSInternalInconsistencyException")
}
}
#import "XCTestCase+Exceptions.h"
import Foundation
extension XCTestCase {
func XCTAssertThrows(expression: @autoclosure () -> (), _ message: String = "") {
ct_XCTAssertThrows(expression, message)
}
func XCTAssertThrowsSpecific(expression: @autoclosure () -> (), _ exceptionName: String, _ message: String = "") {
ct_XCTAssertThrowsSpecific(expression, exceptionName, message)
}
}
@import Foundation;
@import XCTest;
@interface XCTestCase (Exceptions)
- (void)ct_XCTAssertThrows:(void (^)(void))block :(NSString *)message;
- (void)ct_XCTAssertThrowsSpecific:(void (^)(void))block :(NSString *)name :(NSString *)message;
@end
#import "XCTestCase+Exceptions.h"
@implementation XCTestCase (Exceptions)
- (void)ct_XCTAssertThrows:(void (^)(void))block :(NSString *)message {
XCTAssertThrows(block(), @"%@", message);
}
- (void)ct_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
@mpw

This comment has been minimized.

Copy link

commented Aug 15, 2018

To "catch" assert(), you'd need to install a signal handler that catches SIGABRT (or block/ignore it via signal mask).

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.