CodeGhoib
CodeGhoib

Reputation: 23

How to mocking method that calling static class using moq.mock in c#

Say that I have the following code:

public class NumberClass
{
    public NumberClass()
    {
        DefaultNumber = 1;
    }
    public int DefaultNumber{set;get;}
}

public static class NumberSetup
{
    public static NumberClass GetDefaultNumber()
    {
        return new NumberClass();
    }
}

public class NumberSetupImplementation
{
    int FinalNumber;
    public void IncreaseNumber(int currentNumber)
    {
        FinalNumber = currentNumber + NumberSetup.GetDefaultNumber().DefaultNumber;
    }
}

I want to test method NumberSetupImplementation.IncreaseNumber using moq.mock in c#.net, the problem I face is that the method is calling static method.

I have read this, but I don't know how to implement it in my case

Upvotes: 2

Views: 2570

Answers (2)

cuongle
cuongle

Reputation: 75316

Moq uses dynamic proxy under the hood, that is why you cannot use Moq to mock static methods. To design for testability, one of the points is to avoid using static methods. For your example, you can use DI to inject NumberSetup or another trick is to use two constructors:

public interface INumberSetup
{
    NumberClass GetDefaultNumber();
}

public class NumberSetup: INumberSetup 
{ 
    public NumberClass GetDefaultNumber() 
    { 
        return new NumberClass(); 
    } 
} 

public class NumberSetupImplementation 
{ 
    private int _finalNumber;
    private INumberSetup _numberSetup;

    public NumberSetupImplementation()
        : this(new NumberSetup())
    {}

    public NumberSetupImplementation(INumberSetup numberSetup)
    {
        _numberSetup = numberSetup;
    }

    public void IncreaseNumber(int currentNumber) 
    { 
        _finalNumber = currentNumber + _numberSetup.GetDefaultNumber().DefaultNumber; 
    } 
}

Upvotes: 1

aiodintsov
aiodintsov

Reputation: 2605

You have to design your code appropriately to use benefit of Moqs.

Generally this means extensive IoC and clearly separate layers of your application. Main reason for Moq to exist is to rule out deep dependencies so you could concentrate on testing what you created independently of the context. It is true with or without Moq, it just makes it a little easier.

Upvotes: 1

Related Questions