如何部分模拟外部对象 [英] How to partially mock external object

查看:111
本文介绍了如何部分模拟外部对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用于测试依赖对象(键对象)的类方法

I have class method to test with dependant object (Keys object)

APIRouter.m

+ (NSURL*)apiURLWithPath:(NSString*)path {
    MyKeys *keys = [MyKeys new];
    NSString *url = [NSString stringWithFormat:@"%@?api_key=%@", path, [keys APIKey]];
    return [NSURL URLWithString:url];
}

我试图部分模拟此Keys对象并返回"MY_API_KEY"值,但测试方法失败并返回实际的API密钥(例如as78d687as6d7das8da).

I am trying to partially mock this Keys object and return "MY_API_KEY" value but the test method fails and returns real API key (e.g. as78d687as6d7das8da).

APIRouterSpec.m

describe(@"APIRouter", ^{
    it(@"should return url for api", ^{
        Keys *keys = [Keys new];
        id keysPartialMock = OCMPartialMock(keys);
        OCMStub([keysPartialMock APIKey]).andReturn(@"MY_API_KEY");
        NSURL *url = [APIRouter apiURLWithPath:@"http://www.api.com/v1/events"];
        expect([url absoluteString]).to.equal([NSString stringWithFormat:@"http://www.api.com/v1/events?api_key=MY_API_KEY"]);
    });
});

推荐答案

也许这对您有用:

测试方法之外的某个地方:

Somewhere outside your test method:

static NSString *gMockApiKey = @"MY_API_KEY";

将这样的方法存根:

OCMStub([keysPartialMock APIKey]).andDo(^(NSInvocation *invocation)
{
    [invocation setReturnValue:&gMockApiKey];
});

由于APIRouter可能正在使用其自己的Key实例,因此您可以尝试类模拟:

Since APIRouter is probably using its own instance of Keys you can try a class mock:

id keysMock = OCMClassMock([Keys class]);
OCMStub(ClassMethod([keysMock APIKey])).andDo(^(NSInvocation *invocation)
{
    [invocation setReturnValue:&gMockApiKey];
});

所以..我认为模拟它的正确方法是创建一个Keys的模拟实例.

So.. I think the proper way to mock it would be to create a mock instance of Keys.

测试文件顶部的某处:

static Keys *gMockedKeys = nil;
static NSString *gMockApiKey = @"MY_API_KEY";

设置:

- (void)setUp {

    [super setUp];

    gMockedKeys = [Keys new];

    id keysPartialMock = OCMPartialMock(gMockedKeys);
    OCMStub([keysPartialMock APIKey]).andDo(^(NSInvocation *invocation)
    {
        [invocation setReturnValue:&gMockApiKey];
    });
}

测试:

- (void)testAPIURLWithPath {

    id keysMock = OCMClassMock([Keys class]);
    OCMStub([keysMock new]).andReturn(gMockedKeys);

    NSURL *url = [APIRouter apiURLWithPath:@"http://www.api.com/v1/events"];
    NSString *expectedUrlString = [url absoluteString];
    XCTAssertEqualObjects(expectedUrlString, @"http://www.api.com/v1/events?api_key=MY_API_KEY", @"It Should work now..");
}

这篇关于如何部分模拟外部对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆