1

我想测试我在数据库中插入的值是否被发送回我班级的代表。

我试图模拟委托并期望我用来填充数据库的数组。它失败是因为 2 个 NSArray 具有相同的内容但是不同的对象。

我尝试在我的模型上实现 isequal 和 hash 方法但没有成功。

这是错误日志:

'OCMockObject[NewsListViewController]: unexpected method invoked: service:<RSSService-0x4c25b90-324400011.636966: 0x4c25b90> didFinishParsingRSSWithItems:(
    description102362,
    description102362,
    description102362,
    description102362,
    description102362
) 
    expected:   service:<OCMAnyConstraint: 0x4c10f30> didFinishParsingRSSWithItems:(
    description102362,
    description102362,
    description102362,
    description102362,
    description102362
)'

我怎样才能做到这一点 ?

这是我的测试:

- (void) testServiceShouldNotLoadArticlesFromRSSFeedIfArticlesInDatabase {
    NSArray *fakeArticles = [TestUtils createArticles:5];
    [[DatabaseManager sharedManager] saveArticles:fakeArticles];

    RSSService *mockService = [OCMockObject partialMockForObject:service];
    id mockDelegate = [OCMockObject mockForClass:NewsListViewController.class];
    [[mockDelegate expect] service:[OCMArg any] didFinishParsingRSSWithItems:fakeArticles];
    mockService.delegate = mockDelegate;

    [mockService loadAllArticles];
    [mockService verify];
    [mockDelegate verify];
}

这是我正在测试的方法:

- (void) loadAllArticles {
    NSArray *articles = [self articlesFromDatabase];
    [self.delegate service:self didFinishParsingRSSWithItems:articles];
}

谢谢你的帮助,文森特

4

2 回答 2

5

获取OCHamcrest!它提供了一堆与 OCMock 一起工作的匹配器,并且可以进行更清晰的测试。以下是您的期望:

[[mockDelegate expect] service:[OCMArg any] didFinishParsingRSSWithItems:contains(article1, article2, article3, article4, article5, nil)];
// or, if order is unpredictable
[[mockDelegate expect] service:[OCMArg any] didFinishParsingRSSWithItems:containsInAnyOrder(article1, article2, article3, article4, article5, nil)];

如果出于某种原因你真的不想使用 hamcrest,你可以在你的测试类中创建一个方法来评估文章数组。但我认为这有点丑陋:

- (void) testServiceShouldNotLoadArticlesFromRSSFeedIfArticlesInDatabase {
    NSArray *fakeArticles = [TestUtils createArticles:5];
    [[DatabaseManager sharedManager] saveArticles:fakeArticles];

    RSSService *mockService = [OCMockObject partialMockForObject:service];
    id mockDelegate = [OCMockObject mockForClass:NewsListViewController.class];
    [[[mockDelegate stub] andCall:@selector(service:verifyFiveArticles:) onObject:self] service:[OCMArg any] didFinishParsingRSSWithItems:[OCMArg any]];
    mockService.delegate = mockDelegate;

    [mockService loadAllArticles];
    [mockService verify];
    [mockDelegate verify];
}

-(void)service:(id)service verifyFiveArticles:(NSArray *)articles {
    STAssertEquals(5, [articles count]);
}
于 2011-04-14T17:26:24.603 回答
0

这两个数组是否有可能具有相同的内容但不同的地址?也许尝试与isEqualToArray

[[mockDelegate expect] service:[OCMArg any]
  didFinishParsingRSSWithItems:[OCMArg checkWithSelector:@selector(isEqualToArray:)
                                                onObject:expectedArray]]
于 2011-04-13T16:59:23.660 回答