简体   繁体   English

OCMock是一个NSOperation

[英]OCMock an NSOperation

I am trying to write some Unit Tests to test some custom NSOperations that we are writing. 我正在尝试编写一些单元测试来测试我们正在编写的一些自定义NSOperations What I'd like to do is create a Mock of the NSOperation and put it on the NSOperationQueue , and then wait for it to finish. 我想做的是创建NSOperation的模拟并将其放在NSOperationQueue ,然后等待它完成。 I know I can swizzle the methods and not use OCMoc k at all, but I really don't want to do that. 我知道我可以调整方法而根本不使用OCMoc k,但我真的不想这样做。 I'd like to use OCMock . 我想用OCMock The code I'm trying to run is something like the following: 我试图运行的代码如下所示:

MYOperation *operation = [MYOperation new];
id mockOperation = [OCMockObject partialMockForObject:operation];
[NSOperationQueue *queue = [NSOperationQueue new];
[queue setMaxConcurrentOperationCount:1];
[queue addOperation:mockOperation];

When the unit test gets to this line: 当单元测试到达此行时:

[queue addOperation:mockOperation];

I get a call to a deallocated object exception. 我调用了一个解除分配的对象异常。 Anyone have any suggestions on how I can overcome this? 有人对我如何克服这个问题有任何建议吗?

If you're using ARC, operation is probably released right after you create the mock, as it's not accessed again. 如果您正在使用ARC,则可能在创建模拟后立即释放operation ,因为它不会再次访问。 If you change it to this, it should fix the error: 如果将其更改为此,则应修复错误:

[queue addOperation:operation];

...which you should be doing anyways--you're testing your object, not the mock. ...无论如何你应该做的 - 你正在测试你的对象,而不是模拟。

When using ARC the reference to the object in mockOperation will be set to nil quite aggressively (too aggressively I think) by the Apple runtime. 使用ARC时,Apple运行时对mockOperation中对象的引用将被设置为nil(我认为过于激进)。 Not all is lost, though. 但并非所有人都失去了。 You can set up your stubs and expectations using mockOperation and still pass operation to the addOperation: method; 您可以使用mockOperation设置存根和期望,并仍将操作传递给addOperation:方法; the partial mock works even when you use a reference to the original object. 即使您使用对原始对象的引用,部分模拟也会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM