0
我正在使用XCTest做一些C++/OC混合代碼的單元測試。我發現似乎XCTAssertThrows無法捕捉C++異常?XCTAssertThrows可以捕獲C++異常嗎?
我的用法很簡單
說,類似於C++試驗()
XCTAssertThrows(test(), "has throws")
任何建議的表達?
我正在使用XCTest做一些C++/OC混合代碼的單元測試。我發現似乎XCTAssertThrows無法捕捉C++異常?XCTAssertThrows可以捕獲C++異常嗎?
我的用法很簡單
說,類似於C++試驗()
XCTAssertThrows(test(), "has throws")
任何建議的表達?
答案很簡單:自己把它包
龍答:你可以用一個NSException任何的std ::例外,這樣
#import <XCTest/XCTest.h>
#import <exception>
@interface NSException (ForCppException)
@end
@implementation NSException (ForCppException)
- (id)initWithCppException:(std::exception)cppException
{
NSString* description = [NSString stringWithUTF8String:cppException.what()];
return [self initWithName:@"cppException" reason:description userInfo:nil];
}
@end
@interface XCTestCase (ForCppException)
@end
@implementation XCTestCase (ForCppException)
- (void)rethowNSExceptionForCppException:(void(^)())action {
try {
action();
} catch (const std::exception& e) {
@throw [[NSException alloc] initWithCppException:e];
}
}
@end
#define XCTAssertCppThrows(expression, format...) \
XCTAssertThrows([self rethowNSExceptionForCppException:^{expression;}], ## format)
使用方法如下:
#pragma mark - test
void foo() {
throw std::exception();
}
void bar() {
}
@interface testTests : XCTestCase
@end
@implementation testTests
- (void)testExample
{
XCTAssertCppThrows(foo(), @"should thow exception"); // succeed
XCTAssertCppThrows(bar(), @"should thow exception"); // failed
}
@end