OCMock:存根@dynamic属性 [英] OCMock: stub a @dynamic property

查看:223
本文介绍了OCMock:存根@dynamic属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图向现有iOS应用程序添加单元测试,其中使用 OCMock

I'm trying to add unit tests to an existing iOS application, using among others OCMock.

在这个应用程序中,我们有一堆CoreData实体和生成的类。这些类显然包含 @dynamic 属性。

In this application, we have a bunch of CoreData entities and generated classes. These classes obviously contain @dynamic properties.

我试图存根这些属性之一如下:

I tried to stub one of these properties as follows:

self.event = [OCMockObject mockForClass:[ACEvent class]];
[[[self.event stub] andReturn:@"e46e1555-d866-4160-9b42-36d0fb9c29cd"] eventGUID];

关键是,它不工作。显然因为 @dynamic 属性没有默认的实现,在这种情况下依赖CoreData来提供它。我最终得到一个NSError:

The point is, it doesn't work. Apparently because an @dynamic property does not have an implementation by default, and in this case relies on CoreData to provide it. I end up with a NSError:

-[NSProxy doesNotRecognizeSelector:eventGUID] called!

我已经看过其他问题,通过将CoreData实体抽象为协议(< a href =http://stackoverflow.com/questions/1876568/ocmock-with-core-data-dynamic-properties-problem> OCMock与Core Data动态属性问题)。但由于这是一个现有的代码库,我没有这个选项,因为我不能重构一切。

I've seen other questions where this has been solved by abstracting the CoreData entity behind a protocol (OCMock with Core Data dynamic properties problem). But since this is an existing code base, I don't have this option, as I can't afford to refactor everything.

任何人都可以提供另一个解决方案?

Can anyone provide another solution to this?

编辑:
作为附注,我只是找到了一个解决方案,但我担心它不能在所有情况下工作。
我所做的是为测试目标中的这些方法提供一个示例,空实现。它工作,但我担心它可能打破依赖CoreData工作的其他测试。任何洞察这个?

As a side note, I just found a solution, but I'm worried it could not work in all cases. What I did is provide a sample, empty implementation for these methods in the test target. It works, but I'm worried it could break other tests that rely on CoreData to work. Any insight on this?

推荐答案

使用OCMock我总是为每个管理对象创建一个协议,但是你说你不能这样做,所以我建议创建一个假类,你在你想测试的代码中使用相同的属性(对于每个 NSManagedObject ),然后在传递这些假对象时使用一个转换(使用OCMock和存根所需的方法,或者只是创建一个假类的对象并设置所需的属性)。

With OCMock I always create a protocol for each managed object, and then create mocks for those protocols, but as you said you cannot do that, so I suggest to create a fake class with the same properties you are using in the code you want to test(for each NSManagedObject), and then just use a cast when passing those fake objects (either you use OCMock and stub the methods you want or just create a object of the fake class and set the properties you want).

这篇关于OCMock:存根@dynamic属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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