如何使用 OCMock 验证方法调用的数量

发布于 2024-10-26 05:14:35 字数 29 浏览 3 评论 0原文

有没有办法验证一个方法是否已被调用“x”次?

Is there a way to verify that a method has been called 'x' amount of times?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

假装爱人 2024-11-02 05:14:35

查看 OCMock 的测试文件,似乎您需要拥有与呼叫数量相同的 expect 数量。因此,如果你调用 someMethod 三次,你需要做...

[[mock expect] someMethod];
[[mock expect] someMethod];
[[mock expect] someMethod];

...test code...

[mock verify];

虽然这看起来很难看,也许你可以把它们放在一个循环中?

Looking at the test file for OCMock, it seems that you need to have the same number of expects as you have calls. So if you call someMethod three times, you need to do...

[[mock expect] someMethod];
[[mock expect] someMethod];
[[mock expect] someMethod];

...test code...

[mock verify];

This seems ugly though, maybe you can put them in a loop?

终遇你 2024-11-02 05:14:35

我通过利用委托给块的能力取得了成功:

OCMStub([mock someMethod]).andDo(^(NSInvocation *invocation)
{ /* block that handles the method invocation */ });

在块内,我只需增加一个 callCount 变量,然后断言它与预期的调用数量匹配。例如:

- (void)testDoingSomething_shouldCallSomeMethodTwice {
    id mock = OCMClassMock([MyClass class]);

    __block int callCount = 0;
    OCMStub([mock someMethod]).andDo(^(NSInvocation *invocation) {
        ++callCount;
    });

    // ...exercise code...

    int expectedNumberOfCalls = 2;
    XCTAssertEqual(callCount, expectedNumberOfCalls);
}

每次调用 someMethod 时都应调用该块,因此 callCount 应始终与实际调用该方法的次数相同。

I've had success by leveraging the ability to delegate to a block:

OCMStub([mock someMethod]).andDo(^(NSInvocation *invocation)
{ /* block that handles the method invocation */ });

Inside the block, I just increment a callCount variable, and then assert that it matches the expected number of calls. For example:

- (void)testDoingSomething_shouldCallSomeMethodTwice {
    id mock = OCMClassMock([MyClass class]);

    __block int callCount = 0;
    OCMStub([mock someMethod]).andDo(^(NSInvocation *invocation) {
        ++callCount;
    });

    // ...exercise code...

    int expectedNumberOfCalls = 2;
    XCTAssertEqual(callCount, expectedNumberOfCalls);
}

The block should be invoked each time someMethod is called, so callCount should always be the same as the number of times the method was actually called.

无尽的现实 2024-11-02 05:14:35

如果您需要检查一个方法是否只被调用一次,您可以这样做

[self.subject doSomething];
OCMVerify([self.mock method]);

OCMReject([self.mock method]);
[self.subject doSomething];

If you need to check if a method is only called once, you can do it like this

[self.subject doSomething];
OCMVerify([self.mock method]);

OCMReject([self.mock method]);
[self.subject doSomething];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文