简体   繁体   English

如何在MOQ的另一个类单元测试中使用模拟方法

[英]How to use mocked method that in another class Unit Test in MOQ

class CurrentClass
{

    public Task OnStep()
    {
        this.Property = ClassStatic.Method();
    }
}

I have 2 problem : 我有2个问题:

  1. Cannot mock the ClassStatic.Method() because it is static. 无法模拟ClassStatic.Method(),因为它是静态的。
  2. If i can mock the ClassStatic, how to the OnStep() method call ClassStatic.Method() that i was mocked 如果我可以模拟ClassStatic,如何对我模拟的OnStep()方法调用ClassStatic.Method()

Sorry about my english!!! 对不起我的英语!

Use Microsoft Shims to test static methods. 使用Microsoft Shims测试静态方法。 But usually a good idea not to use static classes and methods. 但是通常最好不要使用静态类和方法。 Use dependency injection like so: 像这样使用依赖注入:

class MyClass
{
    IUtility _util;

    public MyClass(IUtility util)
    {
        _util = util;
    }

    public Task OnStep()
    {
       this.Property = _util.Method();
    }
}

public TestMethod()
{
    IUtility fakeUtil = Mock.Of<IUtility>();

    MyClass x = new MyClass(fakeUtil);


}

But if you want to use the static class instead use the shims: 但是,如果要使用静态类,请使用垫片:

using (ShimsContext.Create())
{
    // Arrange:
    // Shim ClassStatic.Method to return a fixed date:
    Namespace.ShimClassStatic.Method = 
    () =>
    { 
      // This will overwrite your static method
       // Fake method here
    };

    // Instantiate the component under test:
    var componentUnderTest = new MyComponent();

    // Act:

    // Assert: 
}

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

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