如何对包含静态方法的方法进行单元测试?
这可以做到吗?这是我正在测试的方法:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不可能使用Rhino Mocks来模拟静态方法 。
然而,这样做是可能的。 Microsoft Moles 和 TypeMock 具有此功能。
我尝试过使用 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.
不可能使用 Rhino Mocks 来模拟静态方法。我要做的就是隔离类中“受保护的内部虚拟”方法中的静态方法。然后你可以做的是模拟“被测类”并模拟“CreateAvatarDirectory”方法。然后调用“SaveAvatarToFileSystem”方法并验证代码是否调用了模拟的“CreateAvatarDirectory”方法。
这是一个非常方便的技巧,允许您隔离被测类中的方法并断言它们被同一类中的其他方法调用。希望有帮助!
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!
您可以编写或使用静态类的现有包装器(在上面的情况下,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).