为什么OCMockpartialMock会破坏KVO? [英] Why does OCMock partialMock break KVO?

查看:81
本文介绍了为什么OCMockpartialMock会破坏KVO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个使用KVO观察某个对象上的属性的对象,然后为该观察者创建了部分模拟,则我将不再收到任何通知.为什么是这样?

If I have an object that uses KVO to observe a property on some object and then create a partial mock for that observer I no longer receive any notifications. Why is this?

这是一个最小的例子:

@interface TestPartialMockAndKVO : SenTestCase
@end
@implementation TestPartialMockAndKVO

- (void)test {
    // Should print "Changed!" when foo property is changed
    MyObserver* myObserver = [[[MyObserver alloc] init] autorelease];

    // But with this line, there is no print out
    [OCMockObject partialMockForObject:myObserver];

    [myObserver setFoo:@"change"];
}

@end

-

@interface MyObserver : NSObject    
@property (copy) NSString* foo;
@end
@implementation MyObserver

- (id)init {
    self = [super init];
    [self addObserver:self forKeyPath:@"foo" options:0 context:NULL];
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    NSLog(@"Changed!");
}

- (void)dealloc { ... }    
@end

推荐答案

KVO和OCMock都在执行一些运行时技巧,从而创建实际类的私有子类来执行其魔术. KVO正在做一个叫做"isa- ",OCMock正在创建一个对象,该对象将成为

Both KVO and OCMock are doing some little runtime tricks whereby they create a private subclass of your actual class in order to perform their magic. KVO is doing a thing called "isa-swizzling", and OCMock is creating an object to be the forwarding target of your original object.

每个系统都有自己的小世界,与自己的类无关. 用OCMock模拟KVO 看起来类似于您的问题.我认为您只需告诉您的模拟对象就能做到这一点

Each system is sort of off in its own little world, with its own class that has nothing to do with the other. Mocking KVO with OCMock looks similar to your problem. I think you should be able to make this work just by telling your mock to

[[myMock expect] observeValueForKeyPath:@"foo"
                               ofObject:myObserver
                                 change:[OCMArg any]
                                context:[OCMArg any]];

这篇关于为什么OCMockpartialMock会破坏KVO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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