如何模拟类方法(+)? [英] How to mock class method (+)?

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

问题描述

需要为以下代码编写单元测试,我想对类方法canMakePayments做模拟,返回是或否,到目前为止,由于canMakePayments没有找到好的方法是类方法(+),似乎所有的OCMock方法都是全部用于实例方法(-).

Need to write unit testing for the following code, I want to do mock for class method canMakePayments, return yes or no, so far no good method found dues to canMakePayments is a class method (+), seems all OCMock methods are all used for instance method (-).

你们的任何建议或讨论将不胜感激.谢谢.

You guys any suggestion or discussion will be appreciated. Thanks.

// SKPaymentQueue.h
// StoreKit
if ([SKPaymentQueue canMakePayments]){
   ....
}
else{
   ...
}

推荐答案

由于您无法通过提供其他实例来拦截该方法,因此您可以为一个类方法提供一个不同的类.像这样:

Since you can't intercept the method by providing a different instance, what you can do for a class method is provide a different class. Something like this:

+ (Class)paymentQueueClass
{
    return [SKPaymentQueue class];
}

呼叫点将变为:

Class paymentQueueClass = [[self class] paymentQueueClass];
if ([paymentQueueClass canMakePayments])
...

这引入了测试接缝"或控制点,使我们可以指定除SKPaymentQueue之外的其他类.现在让我们进行替换:

This introduces a "testing seam," or a point of control, allowing us to specify a class other than SKPaymentQueue. Now let's make a replacement:

static BOOL fakeCanMakePayments;

@interface FakePaymentQueue : SKPaymentQueue
@end

@implementation FakePaymentQueue

+ (void)setFakeCanMakePayments:(BOOL)fakeValue
{
    fakeCanMakePayments = fakeValue;
}

+ (BOOL)canMakePayments
{
    return fakeCanMakePayments;
}

@end

严格来说,这不是模拟对象",而是假对象".区别在于,模拟对象会验证其调用方式.伪造的对象只会提供存根结果.

Strictly speaking, this isn't a "mock object" -- it's a "fake object." The difference is that a mock object verifies how it's called. A fake object just provides stubbed results.

现在,让我们创建要测试的原始类的测试子类.

Now let's create a testing subclass of the original class we want to test.

@interface TestingSubclass : OriginalClass
@end

@implementation TestingSubclass

+ (Class)paymentQueueClass
{
    return [FakePaymentQueue class];
}

@end

所以您看到,这将SKPaymentQueue替换为FakePaymentQueue.现在可以针对TestingSubclass运行测试了.

So you see, this replaces SKPaymentQueue with FakePaymentQueue. Your tests can now run against TestingSubclass.

这篇关于如何模拟类方法(+)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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