Skip to content

Instantly share code, notes, and snippets.

@DivineDominion
Forked from akolov/TestCase.swift
Last active August 15, 2018 09:14
Show Gist options
  • Save DivineDominion/527c9cb4f4563cc9f6b8 to your computer and use it in GitHub Desktop.
Save DivineDominion/527c9cb4f4563cc9f6b8 to your computer and use it in GitHub Desktop.
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
Copy link

mpw 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