是否有令人信服的理由在单元测试中使用DI与模块/类没有依赖关系?

时间:2015-07-23 00:57:41

标签: c# unit-testing dependency-injection language-agnostic dependencies

依赖注入对于测试具有依赖性的模块非常有用。这不是关于那些。

说有一些具体的实施,

public class DoesSomething : IDoesSomething 
{
    public int DoesImportant(int x, int y) 
    { 
        // perform some operation 
    }
}

实现这个,

public interface IDoesSomething
{
    int DoesImportant(int x, int y); 
}

在单元测试中,您显然可以new进行测试,

[TestMethod]
public void DoesSomething_CanDoDoesImportant()
{ 
    int expected = 42; 

    IDoesSomething foo = new DoesSomething(); 
    int actual = foo.DoesImportant(21, 2); 

    Assert.AreEqual(expected, actual); 
}

或使用DI(Autofac在这里,但不应该对问题的原则有关),

[TestMethod]
public void DoesSomething_CanDoDoesImportant()
{
    var builder = new ContainerBuilder();
    builder.RegisterType<DoesSomething>().As<IDoesSomething>();
    var container = builder.Build();

    int expected = 42;
    IDoesSomething foo = container.Resolve<IDoesSomething>();
    int actual = foo.DoesImportant(21, 2);

    Assert.AreEqual(expected, actual);
}

鉴于这样一个没有依赖关系的独立模块,有没有令人信服的理由在测试中注入IDoesSomething?或者,有没有令人信服的理由注入IDoesSomething

2 个答案:

答案 0 :(得分:2)

您的测试应专门针对具体实现编写。

以此为例:

public void DoTestA()
{
    ObjectFactory.Set<IDoesSomething, DoesSomethingBadly>();

    var doesSomething = ObjectFactory.Get<IDoesSomething>();
    Assert.AreEqual(0, doesSomething.Add(1,1));
}

public void DoTestB()
{
    int expected = 42; 

    //This test is now *completely* dependent on DoTestA, and can give different results
    //depending on which test is run first. Further, we don't know
    //which implementation we're testing here. It's not immediately clear, even if
    //there's only one implementation.
    //As its a test, it should be very explicit in what it's testing.

    IDoesSomething foo = ObjectFactory.Get<IDoesSomething>(); 
    int actual = foo.DoesImportant(21, 21); 

    Assert.AreEqual(expected, actual); 
}

// Define other methods and classes here
public class DoesSomething : IDoesSomething 
{
    public int Add(int x, int y) 
    { 
        return x+y;
    }
}

public class DoesSomethingBadly : IDoesSomething
{
    public int Add(int x, int y)
    {
        return x-y;
    }
}

public interface IDoesSomething
{
    int Add(int x, int y); 
}

在测试中,直接引用该类绝对是可行的方法。我们不关心它是一个界面,我们只关心具体的实现。

var foo = new DoesSomething();绝对是更好的选择。

IDoesSomething foo = new DoesSomething();没有害处,但似乎完全不需要,因为我们只关心实现,而不是接口。

答案 1 :(得分:2)

没有需要使用DI容器进行此测试。

这就是为什么你可以使用DI容器来解析具体类的原因:所有其他测试使用类似的模式来通过容器构造类型,而这恰好不需要依赖。

Unity示例:

DoesSomething

这种方法的一个好处是,当{{1}}开始具有依赖关系时,您的测试需要进行最小的更改。