无助级别中的断言

时间:2012-11-21 14:41:38

标签: ios unit-testing assert sentestingkit

我有一个测试用例和一个助手类。在helper类中,我想在这里使用断言:

MainTests.h

#import <SenTestingKit/SenTestingKit.h>

@interface MainTests : SenTestCase

@end

MainTests.m

#import "MainTests.h"
#import "HelperClass.h"

@implementation MainTests

- (void)testExample {
    HelperClass *helperClass = [[HelperClass alloc] init];
    [helperClass fail];
}

@end

HelperClass.h

#import <SenTestingKit/SenTestingKit.h>

@interface HelperClass : SenTestCase

- (void)fail;

@end

HelperClass.m

#import "HelperClass.h"

@implementation HelperClass

- (void)fail {
    STFail(@"This should fail");
}

@end

旁注:我必须使助手类成为SenTestCase的子类,才能访问断言宏。

忽略辅助类的断言。有什么想法吗?如何在辅助类中使用断言?

1 个答案:

答案 0 :(得分:5)

我今天遇到了同样的问题,并提出了一个适用于我的目的的黑客攻击。进入SenTestCase宏,我注意到他们在帮助器上调用[self ...]但没有触发断言。因此,将源类连接到帮助程序让它为我工作。您的问题类的更改如下所示:

<强> MainTests.h

#import <SenTestingKit/SenTestingKit.h>

@interface MainTests : SenTestCase

@end

<强> MainTests.m

#import "MainTests.h"
#import "HelperClass.h"

@implementation MainTests

- (void)testExample {
    // Changed init call to pass self to helper
    HelperClass *helperClass = [[HelperClass alloc] initFrom:self];
    [helperClass fail];
}

@end

<强> HelperClass.h

#import <SenTestingKit/SenTestingKit.h>

@interface HelperClass : SenTestCase

- (id)initFrom:(SenTestCase *)elsewhere;
- (void)fail;

@property (nonatomic, strong) SenTestCase* from;

@end

<强> HelperClass.m

#import "HelperClass.h"

@implementation HelperClass

@synthesize from;

- (id)initFrom:(SenTestCase *)elsewhere
{
    self = [super init];
    if (self) {
        self.from = elsewhere;
    }
    return self;
}

- (void)fail {
    STFail(@"This should fail");
}

// Override failWithException: to use the source test and not self
- (void) failWithException:(NSException *) anException {
    [self.from failWithException:anException];
}

@end

更高级的功能完全有可能需要额外的覆盖,但这对我来说很有用。