如果您无法控制类,您如何模拟类中的方法?

如果您无法控制类,您如何模拟类中的方法?

问题描述:

我使用 Xunit 和 Moq 进行单元测试.到目前为止,我能够成功地模拟和测试来自接口的方法.但是我应该如何模拟和测试我无法控制的类的方法.类没有接口,方法也不是虚拟的.

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.

我研究了 Type Mock Isolator,但我无法完成这项工作,而且这也不是一个可行的解决方案,因为它是付费的并且只有 14 天的试用期,我需要长期这样做.

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.

我有哪些选择?

为依赖项创建包装器.您不需要测试不是您编写的代码的实现.使用预期或假设的输出模拟依赖项包装器.

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);
    }
}