Skip to content

Instantly share code, notes, and snippets.

@ricardopereira
Forked from DivineDominion/TestCase.swift
Created August 14, 2018 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricardopereira/8cb20882906312b9fc10c882de39b6f9 to your computer and use it in GitHub Desktop.
Save ricardopereira/8cb20882906312b9fc10c882de39b6f9 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment