Skip to main content
 首页 » 编程设计

c#之单元测试 c# 模拟接口(interface)由另一个接口(interface)组成

2024年02月05日14虾米姐

我是编码新手。

我有一个类(class),A:

public class A  
{ 
    public InterfaceB _b;    
 
    public A()  
    {   
        _b = new B();  
    }  
 
    public string functionA()  
    { 
        if(String.IsNullOrEmpty(_b.GetId()))  
            return String.Empty; 
        else if(String.IsNullOrEmpty(_b.GetKey()))  
            return String.Empty; 
        else   
            return _b.GetToken();  
    }  
}  
 
public interface InterfaceB  
{     
    string GetId();    
    string GetKey();  
    string GetToken(); 
} 

我想测试functionA,在那里我可以渗透到interfaceB的所有三个方法。在我的单元测试中,我创建了类 A 的实例,当我调用它时,我无法设置类 B 的行为。

它不断命中数据库,但我需要它用于其他测试用例。

我如何完全模拟它以便我可以测试整个逻辑?

请您参考如下方法:

为了能够测试 A 和模拟接口(interface) InterfaceB 你必须编写 A 以便它不负责创建一个实例接口(interface) B。相反,它通过其构造函数接收 InterfaceB 的实例。

您会一遍又一遍地看到这种模式:

public A()  
{   
    private readonly InterfaceB _b; 
 
    public A(InterfaceB b) 
    { 
        _b = b; 
    } 
 
    public string functionA()  
    { 
        if(String.IsNullOrEmpty(_b.GetId())) return String.Empty; 
        else if(String.IsNullOrEmpty(_b.GetKey())) return String.Empty; 
        else  return _b.GetToken();  
     }  
}  

这称为依赖注入(inject)。这意味着一个类的依赖被“注入(inject)”到它而不是创建它的那个类。当我们像这样注入(inject)构造函数时,我们也称之为“构造函数注入(inject)”,但通常它只是“依赖注入(inject)”。能够像您所询问的那样模拟接口(interface)是我们使用它的原因之一。

一些关键细节:

  • 因为 InterfaceB 被传递给构造函数,所以 A 中的任何内容都“不知道”实际实现是什么。它可以是任何东西。因此,A 永远不会绑定(bind)到任何具体实现。 (这就是为什么您可以“模拟”InterfaceB。)
  • 字段_b 是只读。这不是绝对必要的,但这意味着 _b 只能从构造函数中设置并且永远不会再次更改。这强调 A 仅接收并使用它。此类从不控制 _b 是什么。无论创建 A 都决定了该值是什么。

现在,当您编写单元测试时,您可以创建 InterfaceB 的模拟实现,它完全符合您的要求,例如

public class MockedInterfaceB : InterfaceB 
{ 
    private string _id; 
    private string _key; 
    private string _token; 
 
    public MockedInterfaceB(string id, string key, string token); 
    { 
       _id = id; 
       _key = key; 
       _token = token; 
    } 
    public string GetId() {return _id};    
    public string GetKey() {return _key};  
    public string GetToken() {return _token}; 
} 

然后在您的单元测试中您可以使用该实现:

var testA = new A(new MockedInterfaceB("myid","mykey","mytoken")); 

您还可以使用 Moq 等工具更轻松地创建这些模拟。

当您听说依赖注入(inject)时,通常是在依赖注入(inject)容器(如 CaSTLe Windsor、Autofac 或 Unity)的上下文中。这些是帮助您使依赖注入(inject)工作的有用工具。他们值得学习。但是依赖注入(inject)实际上只是关于如何编写类,就像上面的示例中我们将依赖项 (InterfaceB)“注入(inject)”到类 A 中一样。