简体   繁体   English

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

[英]How do I unit test a method containing a static method?

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. 在单元测试中,我正在使用Rhino.Mocks,我想验证_file.SaveAs()是否被调用。 I've mocked out _file (which is an HttpPostedFileBase object) and injected it into this method's class constructor. 我模拟了_file(这是一个HttpPostedFileBase对象),并将其注入到此方法的类构造函数中。 I want to run this unit test, but not actually have the Directory.CreateDirectory call get made. 我想运行此单元测试,但实际上没有进行Directory.CreateDirectory调用。 Is this possible? 这可能吗?

It is not possible to mock a static method using Rhino Mocks . 使用Rhino Mocks无法模拟静态方法

However, it is possible to do this. 但是,可以这样做。 Microsoft Moles and TypeMock have this capability. Microsoft MolesTypeMock具有此功能。

I have tried using Moles, and it works alright. 我已经尝试过使用Moles,而且效果很好。 It generates a mock assembly for you, and you are able to replace a static method at runtime with a delegate. 它会为您生成一个模拟程序集,并且您可以在运行时使用委托替换静态方法。

Its not possible to mock a static method using Rhino Mocks. 使用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. 然后,您可以模拟“正在测试的类”并模拟“ CreateAvatarDirectory”方法。 Then call the "SaveAvatarToFileSystem" method and verify that the code called your mocked "CreateAvatarDirectory" method. 然后,调用“ SaveAvatarToFileSystem”方法,并验证代码是否调用了模拟的“ CreateAvatarDirectory”方法。

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);
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM