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