我正在尝试为我创建的简单UIDevice类别设置一些测试用例。 由于这些方法是实例方法,我创建了一个模拟来模拟currentDevice行为。 添加的方法基于name属性,因此我创建了一个存根以在name属性上返回假名。
存根很有效,但如果我尝试访问其他方法,我会得到非模拟名称属性。
这是我的测试用例:
#import "UIDevice_NameFromDevice_Tests.h"
#import <OCMock/OCMock.h>
#import "UIDevice+UnitTests.h"
#import "UIDevice+NameFromDevice.h"
@implementation UIDevice_NameFromDevice_Tests
-(void)setUp
{
self.firstName = @"John";
self.lastName = @"Doe";
self.fullName = [NSString stringWithFormat:@"%@ %@",self.firstName,self.lastName];
self.mockedDevice = [UIDevice createNicelyMockedCurrentDevice];
}
-(void)tearDown
{
self.firstName = nil;
self.lastName = nil;
self.fullName = nil;
[UIDevice releaseInstance];
}
#pragma mark UIDevice mock checks
-(void)test_mockedDevice_shouldBeEqualToCurrentDevice
{
self.mockedDevice = [UIDevice createMockedCurrentDevice];
STAssertEqualObjects(self.mockedDevice, [UIDevice currentDevice], nil);
}
-(void)test_stubedDeviceName_shouldBeEqualToCurrentDeviceName
{
NSString *format = @"%@ %@'s iPhone";
NSString *fakeiPhoneName = [NSString stringWithFormat:format,self.firstName,self.lastName];
[[[self.mockedDevice stub] andReturn:fakeiPhoneName] name];
STAssertEqualObjects([self.mockedDevice name], [[UIDevice currentDevice] name], nil);
STAssertEqualObjects([[UIDevice currentDevice] name], fakeiPhoneName, nil);
}
#pragma mark test langages
-(void)test_BasicENName_shouldReturnValues
{
NSString *fakeiPhoneName = [NSString stringWithFormat:@"%@'s iPhone", self.fullName];
[[[self.mockedDevice stub] andReturn:fakeiPhoneName] name];
NSLog(@"name : %@",[[UIDevice currentDevice] name]);
NSLog(@"fullname : %@",[[UIDevice currentDevice] fullNameFromDevice]);
NSLog(@"firstname : %@",[[UIDevice currentDevice] firstName]);
NSLog(@"lastname : %@",[[UIDevice currentDevice] lastName]);
STAssertEqualObjects([self.mockedDevice name], [[UIDevice currentDevice] name], nil);
STAssertEqualObjects([[UIDevice currentDevice] name], fakeiPhoneName, nil);
// STAssertEqualObjects([[UIDevice currentDevice] fullNameFromDevice], self.fullName, nil);
// STAssertEqualObjects([[UIDevice currentDevice] firstName], self.firstName, nil);
// STAssertEqualObjects([[UIDevice currentDevice] lastName], self.lastName, nil);
}
@end
这是完整的代码:https://github.com/tiboll/TLLNameFromDevice/
(3个评论断言不起作用)
有没有人有任何想法?
答案 0 :(得分:0)
要修复这些项目,请执行以下操作。
在UIDevice+UnitTests.m
添加以下方法:
+(id)createPartialMockedCurrentDevice
{
_mockedCurrentDevice = [OCMockObject partialMockForObject:[UIDevice currentDevice]];
return _mockedCurrentDevice;
}
删除以下方法:
+(UIDevice *)currentDevice
{
if (_mockedCurrentDevice)
return _mockedCurrentDevice;
return invokeSupersequentNoParameters();
}
从方法
中删除以下语句 -(NSString *)fullNameFromDevice in class UIDevice+NameFromDevice.m
if (_name)
return _name;