How can you mock the methods from a class if you have no control over the class?
Asked Answered
B

1

5

I'm using Xunit and Moq for unit testing. So far I was able to succesfully mock and test methods from interfaces. But how am I supposed to mock and test the methods of a class that I have no control over. The class has no interface and the methods are not virtual.

I looked into Type Mock Isolator, but I could not make that work, and also that is not a feasible solution because it's paid and only has a 14 day trial, and I need to do this long term.

What are my options?

Berndt answered 21/1, 2021 at 17:35 Comment(1)
There are many free alternatives: Prig, Pose, Harmony, MethodRedirect, Ionad.FodyWeathering
E
8

Create a wrapper for the dependency. You don't need to test the implementation of code you didn't write. Mock the dependency wrapper with the anticipated or hypothetical outputs.

public sealed class SomeBadDependency
{
    public int CalculateSuperSecretValue(int inputX, int inputY)
    {
        return Math.Max(inputX, inputY);
    }
}

public interface IDependencyWrapper
{
    int CalculateSuperSecretValue(int inputX, int inputY);
}

public sealed class DependencyWrapper : IDependencyWrapper
{
    private readonly SomeBadDependency _someBadDependency;

    public DependencyWrapper(SomeBadDependency someBadDependency)
    {
        _someBadDependency = someBadDependency;
    }
    
    public int CalculateSuperSecretValue(int inputX, int inputY)
    {
        return _someBadDependency.CalculateSuperSecretValue(inputX, inputY);
    }
}

public sealed class YourCode
{
    private readonly IDependencyWrapper _dependencyWrapper;

    public YourCode(IDependencyWrapper dependencyWrapper)
    {
        _dependencyWrapper = dependencyWrapper;
    }

    public decimal CalculateYourValue(decimal inputX, decimal inputY)
    {
        return _dependencyWrapper.CalculateSuperSecretValue((int) inputX, (int) inputY);
    }
}
Ewen answered 21/1, 2021 at 18:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.