我該如何在init方法中使用一個方法?如何使用OCMock初始化一個帶有殘值的對象
的相關方法在我的課:
- (id)init
{
self = [super init];
if (self) {
if (self.adConfigurationType == AdConfigurationTypeDouble) {
[self configureForDoubleConfiguration];
}
else {
[self configureForSingleConfiguration];
}
}
return self;
}
- (AdConfigurationType)adConfigurationType
{
if (adConfigurationType == NSNotFound) {
if ((random()%2)==1) {
adConfigurationType = AdConfigurationTypeSingle;
}
else {
adConfigurationType = AdConfigurationTypeDouble;
}
}
return adConfigurationType;
}
我的測試:
- (void)testDoubleConfigurationLayout
{
id mockController = [OCMockObject mockForClass:[AdViewController class]];
AdConfigurationType type = AdConfigurationTypeDouble;
[[[mockController stub] andReturnValue:OCMOCK_VALUE(type)] adConfigurationType];
id controller = [mockController init];
STAssertNotNil([controller smallAdRight], @"Expected a value here");
STAssertNotNil([controller smallAdRight], @"Expected a value here");
STAssertNil([controller largeAd], @"Expected nil here");
}
我的結果:
終止應用程序由於未捕獲的異常 'NSInternalInconsistencyException',理由是:「OCMockObject [ AdViewController]:調用的意外方法:smallAdRight'
那麼如何訪問OCMockObject中的AdViewController?
做了兩個小編輯克勞斯的答案,但本質上提出的測試執行現在應該通過 – nduplessis
有時你的init方法只執行一次配置,而你想測試的路徑將不會用這種方法執行。如果您只是在第一行中調用[AdViewController alloc],那麼這種測試通常也起作用。 –
再次閱讀您的文章,現在很明顯,在控制器被嘲笑之前,您不應該調用init。我沒有注意到你第一次通過屬性實際上對adConfigurationType進行了隱式調用。我編輯了我的帖子,以更好地反映這一點。 –