【问题标题】:How can you mock the methods from a class if you have no control over the class?如果您无法控制类,您如何模拟类中的方法?
【发布时间】:2021-04-26 04:33:01
【问题描述】:

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

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

我有什么选择?

【问题讨论】:

标签: c# unit-testing moq xunit


【解决方案1】:

为依赖项创建一个包装器。您无需测试您未编写的代码的实现。使用预期或假设的输出模拟依赖包装。

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

【讨论】:

    猜你喜欢
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    相关资源
    最近更新 更多