使用NMock C#注入接口数组

时间:2017-07-18 18:49:18

标签: c# unit-testing nunit

我是NUnit的新手,对于如何在测试对象的构造函数中注入Interface对象数组有疑问。例如:

Class Class1 
{
   private ITest[] iTests;
   private ITest1 iTest1;

   Class1(ITest1 iTest1, ITest[] iTests)
   {
      this.iTests = iTests;
      this.iTest1 = iTest1;
   }
}

[TestFixture()]
class Class1UnitTest
{
    private Mock<ITest1> iTest1;
    private Class1 class1;

    [SetUp]
    public void setUp ()
    {
      this.iTest1 = new Mock<ITest1>();
      class1 = new Class1 (this.iTest1.Objeсt, ????);
    }
}

有人可以告诉我如何在单元测试中注入ITest []吗?

先谢谢。

1 个答案:

答案 0 :(得分:1)

只需创建一个数组并使用您之前创建的模拟填充模拟。

[TestFixture()]
class Class1UnitTest {
    private Mock<ITest1> iTest1;
    private ITest[] iTests;
    private Class1 class1;

    [SetUp]
    public void setUp () {
      this.iTest1 = new Mock<ITest1>();

      var mock1 = new Mock<ITest>();
      var mock2 = new Mock<ITest>();
      var mock3 = new Mock<ITest>();

      this.iTests = new ITest[] {
          mock1.Object,
          mock2.Object,
          mock3.Object,
          //...
      }
      class1 = new Class1 (this.iTest1.Objeсt, this.iTests);
    }
}

你甚至可以创建一个帮助方法来干掉代码

public T[] MockArray<T>(int length) where T : class {
    return Enumerable.Range(0, length).Select(i => new Mock<T>().Object).ToArray();
}

并在测试中调用它

this.iTests = MockArray<ITest>(5);