为什么这个OCUnit测试失败了?

时间:2012-09-28 19:50:06

标签: objective-c ios mocking tdd ocunit

它正在进入主视图控制器的ViewDidLoad,并且命中行调用获取所有推文,但是我在基数和派生的getAllTweets中放置一个断点,看看它是不是像我一样没有击中派生预期

@implementation WWMainViewControllerTests {

    // system under test
    WWMainViewController *viewController;

    // dependencies
    UITableView *tableViewForTests;
    WWTweetServiceMock *tweetServiceMock;    
}

- (void)setUp {

    tweetServiceMock = [[WWTweetServiceMock alloc] init];
    viewController = [[WWMainViewController alloc] init];
    viewController.tweetService = tweetServiceMock;
    tableViewForTests = [[UITableView alloc] init];
    viewController.mainTableView = tableViewForTests;
    tableViewForTests.dataSource = viewController;
    tableViewForTests.delegate = viewController;
}

- (void)test_ViewLoadedShouldCallServiceLayer_GetAllTweets {

    [viewController loadView];
    STAssertTrue(tweetServiceMock.getAllTweetsCalled, @"Should call getAllTweets on tweetService dependency");
}

- (void)tearDown {

    tableViewForTests = nil;
    viewController = nil;
    tweetServiceMock = nil;
}

基本推文服务:

@implementation WWTweetService {

    NSMutableArray *tweetsToReturn;
}

- (id)init {

    if (self = [super init]) {
        tweetsToReturn = [[NSMutableArray alloc] init];
    }

    return self;
}
- (NSArray *)getAllTweets {

    NSLog(@"here in the base of get all tweets");
    return tweetsToReturn;
}

@end

模拟推文服务:

@interface WWTweetServiceMock : WWTweetService

@property BOOL getAllTweetsCalled;

@end

@implementation WWTweetServiceMock

@synthesize getAllTweetsCalled;

- (id)init {

    if (self = [super init]) {
        getAllTweetsCalled = NO;
    }

    return self;
}

- (NSArray *)getAllTweets {

    NSLog(@"here in the mock class.");
    getAllTweetsCalled = YES;
    return [NSArray array];
}

正在测试的主视图控制器:

@implementation WWMainViewController
@synthesize mainTableView = _mainTableView;
@synthesize tweetService;

NSArray *allTweets;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    allTweets = [tweetService getAllTweets];
    NSLog(@"was here in view controller");
}

- (void)viewDidUnload
{
    [self setMainTableView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

1 个答案:

答案 0 :(得分:1)

由于您可以在viewDidLoad中打破调试器,tweetService ivar的价值是多少?如果是nil,则getAllTweets消息将只是一个无操作。也许ivar没有被正确设置或在其他地方被覆盖。

您应该使用该属性来访问tweetService(调用self.tweetService)而不是其底层的ivar。您应该只在getter,setter和init中直接访问ivar(如果由于某些疯狂的原因没有使用ARC,也可以dealloc。)

您也不应该自己调用loadView,而只需访问视图控制器的view属性。这将启动加载过程并致电viewDidLoad

另外,如果你做了很多嘲笑,我强烈推荐OCMock