我想测试我在数据库中插入的值是否会发送回我班级的代表。
我试图模拟委托并期望我用来填充数据库的数组。它失败了,因为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];
}
感谢您的帮助, 文森特
答案 0 :(得分: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,可以在测试类中创建一个评估articles数组的方法。但我认为这有点难看:
- (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]);
}
答案 1 :(得分:0)
这两个数组是否可能具有相同的内容但地址不同?也许尝试与isEqualToArray
[[mockDelegate expect] service:[OCMArg any]
didFinishParsingRSSWithItems:[OCMArg checkWithSelector:@selector(isEqualToArray:)
onObject:expectedArray]]