在同一方法上调用 OCMStub 和 OCMReject

Calling OCMStub and OCMReject on the same method

我一直在尝试使用 OCMReject 编写一些快速失败测试。但是我发现如果 OCMStub 与 OCMReject 一起使用,这个测试将通过

id _mockModel = OCMProtocolMock( @protocol( CTPrefModelProtocol));
//It doesn't seem to matter what order these two are in, the test behaves the same
OCMStub([_mockModel getPreferences]);
OCMReject([_mockModel getPreferences]);
[_mockModel getPreferences];

尽管它显然应该失败,因为我正在调用我在 OCMReject 方法中设置的函数。

我意识到我可以在需要结果时对 getPreferences 进行存根并将其从该测试中删除,但这主要意味着如果我在 setUp 方法中对 getPreferences 设置了存根,任何调用的测试OCMReject([_mockModel getPreferences]) 将被忽略。

为什么我不能同时使用 OCMStub 和 OCMReject?是因为 OCMStub 以某种方式改变了 getPreferences,结果每当我调用这个方法时,它实际上调用了其他方法吗?

看来我不识字了。通读 OCMock 3 文档,在限制标题 10.2

Setting up expect after stub on the same method does not work

id mock = OCMStrictClassMock([SomeClass class]);
OCMStub([mock someMethod]).andReturn(@"a string");
OCMExpect([mock someMethod]);

/* run code under test */

OCMVerifyAll(mock); // will complain that someMethod has not been called

The code above first sets up a stub for someMethod and afterwards an expectation for the same method. Due to the way mock objects are currently implemented any calls to someMethod are handled by the stub. This means that even if the method is called the verify fails. It is possible to avoid this problem by adding andReturn to the expect statement. You can also set up a stub after the expect.

我怀疑 OCMReject 也存在同样的限制。希望这能帮助像我这样的盲人。懒人的 link to the documentation