简体   繁体   中英

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 :

  1. Cannot mock the ClassStatic.Method() because it is static.
  2. If i can mock the ClassStatic, how to the OnStep() method call ClassStatic.Method() that i was mocked

Sorry about my english!!!

Use Microsoft Shims to test static methods. 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: 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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