Created
September 18, 2014 12:37
-
-
Save akolov/8894408226dab48d3021 to your computer and use it in GitHub Desktop.
Testing for XCTAssertThrows in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "XCTestCase+Exceptions.h" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@import Foundation; | |
@import XCTest; | |
@interface XCTestCase (Exceptions) | |
- (void)XCTAssertThrows:(void (^)(void))block :(NSString *)message; | |
- (void)XCTAssertThrowsSpecific:(void (^)(void))block :(NSString *)name :(NSString *)message; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. I got a little confused with the example that was shown, to use your solution I had to code something like this: