2

我正在尝试为我创建的简单 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个评论断言不起作用)

有人有什么主意吗?

4

1 回答 1

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;
于 2013-10-11T19:52:19.060 回答