如何断言 RhinoMocks 中的一个方法是否在另一个方法中被调用?

发布于 2024-08-31 02:48:25 字数 333 浏览 2 评论 0原文

我有一个有两种方法的类。一种方法需要调用另一种方法,在我的测试中我想断言它已被调用。

public class Tasks : ITasks
{
  public void MethodOne()
  {
    MethodTwo(1);
  }

  public int MethodTwo(int i)
  {
    return i + 1;
  }
}

我想模拟 Tasks 并执行类似 tasks.AssertWasCalled(x => x.MethodTwo(1)) 的操作。 MethodTwo 必须是虚拟的吗?

I have a class that has two methods. One method needs to call the other method and in my test I want to assert that it was called.

public class Tasks : ITasks
{
  public void MethodOne()
  {
    MethodTwo(1);
  }

  public int MethodTwo(int i)
  {
    return i + 1;
  }
}

I want to mock Tasks and do something like tasks.AssertWasCalled(x => x.MethodTwo(1)). Must MethodTwo be virtual?

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

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

发布评论

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

评论(2

清君侧 2024-09-07 02:48:25

您正在寻找的概念是 部分模拟 (这显示旧语法,但我不记得新语法了)。你应该仔细阅读它。本质上,您在任务(而不是ITask)上创建模拟并告诉它仅模拟MethodTwo(需要是虚拟的)。

但是......您可能需要重新考虑您的设计。什么是 ITask?作用是什么?它们的实际任务不同吗?您有什么理由希望他们在同一个班级吗?我的理解是,仅当您需要测试遗留组件时才包含部分模拟 - 我从未发现它有什么用途。

The concept you're looking for is partial mocks (this shows old syntax, but I don't remember the new one off the top of my head). You should read up on it. Essentially you create the mock on Tasks (not ITasks) and tell it to mock out only MethodTwo (which needs to be virtual).

However...you might want to reconsider your design. What is ITasks? What is the role? Are they different actual tasks? Is there any reason why you would want them in the same class? My understanding is that partial mocks is only included for when you need to test legacy components - I've never found a use for it.

青朷 2024-09-07 02:48:25

当然我当时的想法是有问题的。我应该嘲笑 ITasks,而不是实现(任务):

ITasks tasks = MockRepository.GenerateMock<ITasks>();
tasks.AssertWasCalled(x => x.MethodTwo(Arg<int>.Is.Equal(1)));

Of course my thinking at that time was flawed. I should be mocking ITasks, not the implementation (Tasks):

ITasks tasks = MockRepository.GenerateMock<ITasks>();
tasks.AssertWasCalled(x => x.MethodTwo(Arg<int>.Is.Equal(1)));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文