是否可以将代码重用于集成和单元测试?

ole*_*sii 5 c# language-agnostic tdd integration-testing unit-testing

我使用具有单元测试和集成测试的分布式系统。我试图通过在集成和单元测试之间重用代码来节省时间和维护工作。为此,我实现了一个接口和2个类:伪类和真实类。类返回一些存根数据,而类则对其他分布式服务进行一些调用。

我项目的当前结构

/ BaseTest              
   接口IFoo
-------------------------------------
/单元测试
   FakeFoo类:IFoo

   [TestFixture]
   class FooTest {...} //使用FakeFoo
-------------------------------------
/集成测试
   RealFoo类:IFoo

   [TestFixture]
   class FooTest {...} //使用RealFoo

我想以某种方式重用两个测试的代码,所以如果我有一个测试

[Test]
public void GetBarIsNotNullTest()
{
    var foo = IoC.Current.Resolve<IFoo>();
    Bar actual = foo.GetBar();
    Assert.IsNotNull(actual);   
}
Run Code Online (Sandbox Code Playgroud)

我希望此测试可同时在RealFoo和和两种实现下运行FakeFoo。到目前为止,我已经考虑过在/ UnitTest/ IntegrationTest项目之间进行复制粘贴测试,但这听起来不对。

系统是用C#编写的,但是我相信这个问题与语言无关。

有人有更好的主意吗?我做错了吗?

ole*_*sii 5

即使其他人的回答很不错,但这也是我最终要做的

我为单元和集成测试创建了一个基类

[TestFixture]
public class FooBase
{
    [Test]
    public void GetBarIsNotNullTest()
    {
        var foo = IoC.Current.Resolve<IFoo>();
        Bar actual = foo.GetBar();
        Assert.IsNotNull(actual);   
    }

    //many other tests  
}
Run Code Online (Sandbox Code Playgroud)

然后从派生两个类FooBase。这些课程只会包含SetUp和,而没有其他内容。即:

[TestFixture]
public class UnitTestFoo : FooBase
{
    [SetUp]
    public void SetUp()
    {
        IoC.Current.Register<IFoo, FakeFoo>();        
    }

    //nothing else here
}

[TestFixture]
public class IntegrationTestFoo : FooBase
{
    [SetUp]
    public void SetUp()
    {
        IoC.Current.Register<IFoo, RealFoo>();        
    }

    //nothing else here
}
Run Code Online (Sandbox Code Playgroud)

因此,如果现在运行测试,我将在父类中定义的测试FooBase针对单元测试类和集成测试类运行两次,并使用它们自己的真实对象。这是因为测试治具的继承。