Frage

I am using XCTest to do unit test of some c++/OC mixed codes. I found it seems that XCTAssertThrows cannot catch c++ exception?

My usage is very simple

say, an expression like in c++ test()

XCTAssertThrows(test(), "has throws")

Any suggestion?

War es hilfreich?

Lösung

Short Answer: wrap it by yourself


Long Answer: you can wrap an NSException for any std::exception, like this

#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)

Use it like this:

#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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top