Thinh
Thinh

Reputation: 15

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!!!

Upvotes: 1

Views: 628

Answers (1)

dburner
dburner

Reputation: 1007

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: 
}

Upvotes: 2

Related Questions