如何对包含静态方法的方法进行单元测试?

发布于 2024-09-30 11:46:03 字数 346 浏览 0 评论 0原文

这可以做到吗?这是我正在测试的方法:

public void SaveAvatarToFileSystem()
{
  Directory.CreateDirectory(AvatarDirectory);
  _file.SaveAs(FormattedFileName);
}

在我的单元测试中,我使用 Rhino.Mocks 并且我想验证 _file.SaveAs() 是否被调用。我已经模拟了 _file (这是一个 HttpPostedFileBase 对象)并将其注入到该方法的类构造函数中。我想运行此单元测试,但实际上没有进行 Directory.CreateDirectory 调用。这可能吗?

Can this be done? Here is the method I'm testing:

public void SaveAvatarToFileSystem()
{
  Directory.CreateDirectory(AvatarDirectory);
  _file.SaveAs(FormattedFileName);
}

In my unit test, I'm using Rhino.Mocks and I want to verify that _file.SaveAs() was called. I've mocked out _file (which is an HttpPostedFileBase object) and injected it into this method's class constructor. I want to run this unit test, but not actually have the Directory.CreateDirectory call get made. Is this possible?

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

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

发布评论

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

评论(3

帅冕 2024-10-07 11:46:03

不可能使用Rhino Mocks来模拟静态方法

然而,这样做是可能的。 Microsoft MolesTypeMock 具有此功能。

我尝试过使用 Moles,效果还不错。它为您生成一个模拟程序集,并且您可以在运行时用委托替换静态方法。

It is not possible to mock a static method using Rhino Mocks.

However, it is possible to do this. Microsoft Moles and TypeMock have this capability.

I have tried using Moles, and it works alright. It generates a mock assembly for you, and you are able to replace a static method at runtime with a delegate.

壹場煙雨 2024-10-07 11:46:03

不可能使用 Rhino Mocks 来模拟静态方法。我要做的就是隔离类中“受保护的内部虚拟”方法中的静态方法。然后你可以做的是模拟“被测类”并模拟“CreateAvatarDirectory”方法。然后调用“SaveAvatarToFileSystem”方法并验证代码是否调用了模拟的“CreateAvatarDirectory”方法。

这是一个非常方便的技巧,允许您隔离被测类中的方法并断言它们被同一类中的其他方法调用。希望有帮助!

public void SaveAvatarToFileSystem()
{
    CreateAvatarDirectory();
    _file.SaveAs(FormattedFileName);
}

protected internal virtual void CreateAvatarDirectory()
{
    Directory.CreateDirectory(AvatarDirectory);
}

Its not possible to mock a static method using Rhino Mocks. What I would do is isolate the static method in "protected internal virtual" method in the class. Then what you can do is mock the "Class Under Test" and mock the "CreateAvatarDirectory" method. Then call the "SaveAvatarToFileSystem" method and verify that the code called your mocked "CreateAvatarDirectory" method.

Its a very handy trick that allows you to isolate methods in your class under test and assert they were called by other methods in the same class. Hope that helps!

public void SaveAvatarToFileSystem()
{
    CreateAvatarDirectory();
    _file.SaveAs(FormattedFileName);
}

protected internal virtual void CreateAvatarDirectory()
{
    Directory.CreateDirectory(AvatarDirectory);
}
熊抱啵儿 2024-10-07 11:46:03

您可以编写或使用静态类的现有包装器(在上面的情况下,System.IO.Abstractions 可能会帮助)。

You could write or using an existing wrapper for the static class (in the case above maybe System.IO.Abstractions will help).

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