我如何对适配器类进行单元测试?

问题描述 投票:0回答:1

假设我有来自第三方库的以下类:

public class ThirdPartyType { ... }

public class ThirdPartyFunction
{
    public ThirdPartyType DoSomething() { ... }
}

实现细节并不重要,它们实际上不在我对此第三方库的控制范围之内。

假设我为ThirdPartyFunction编写了一个适配器类:

public class Adapter
{
    private readonly ThirdPartyFunction f;

    public Adapter()
    {
        f = new ThirdPartyFunction();
    }

    public string DoSomething()
    {
        var result = f.DoSomething();

        // Convert to a type that my clients can understand
        return Convert(result);
    }

    private string Convert(ThirdPartyType value)
    {
        // Complex conversion from ThirdPartyType to string
        // (how do I test this private method?)
        ...
    }
}

如何测试Convert(ThirdPartyType)的实现是否正确? Adapter类只需要它,这就是为什么它是私有方法的原因。

c# unit-testing nunit xunit
1个回答
0
投票

我建议将代码提取到单独的类中,然后测试该类。尽管此Adapter仅使用它,但适配器也不应该负责进行转换(与“单一职责原则”保持一致)。

通过将其提取出来,可以独立于第三方代码测试转换器。

如果转换器不需要任何状态,您也可以将其设为静态类,然后直接在适配器中对其进行引用,而无需通过依赖注入进行注册。

© www.soinside.com 2019 - 2024. All rights reserved.