Skip to main content
 首页 » 编程设计

c#之测试单个接口(interface)的不同具体实现

2024年02月05日8xiaohuochai

我有以下代码:

public interface IFoo 
{ 
    IResult ResolveTheProblem(IBar inputData); 
} 
 
public class FastFoo : IFoo 
{ 
    public IResult ResolveTheProblem(IBar inputData) 
    { 
        // Algorithm A - resolves the problem really fast 
    } 
} 
 
public class SlowFoo : IFoo 
{ 
    public IResult ResolveTheProblem(IBar inputData) 
    { 
        // Algorithm B - different algoritm, resolves the problem slow 
    } 
} 

要测试的最重要的事情是每个算法的实现。 为了进行测试,我使用了 NUnit 和 NSubstitute。现在我有这样的测试:

    [Test] 
    public void FooTest() 
    { 
        IFoo foo = Substitute.For<IFoo>(); 
        IBar bar = Substitute.For<IBar>(); 
 
        IResult result = foo.ResolveTheProblem(bar); 
 
        Assert.IsNotNull(result); 
    } 

我的两个问题:

  • 这个测试有必要吗?我不确定
  • 如何测试每个 IFoo(FastFoo 和 SlowFoo)的实现?

编辑:FastFoo 和 SlowFoo 是两个完全不同的实现。两者的结果都是一个从1到10的随机数。

请您参考如下方法:

不,没有必要。为什么要测试替代实现? 您替换您的依赖项,例如 IBar。 你测试你的具体实现:

[Test]     
public void SlowFooTest() 
{     
    IBar bar = Substitute.For<IBar>(); 
    // Setup bar expectations / canned responses as required 
    var foo = new SlowFoo(bar); 
    IResult result = foo.ResolveTheProblem(bar); 
    // Validate result from concrete class: 
    Assert.IsNotNull(result); 
} 
 
[Test]     
public void FastFooTest() 
{     
    IBar bar = Substitute.For<IBar>(); 
    var foo = new FastFoo(bar); 
    IResult result = foo.ResolveTheProblem(bar); 
    Assert.IsNotNull(result); 
}