Nsubstitute:为单元测试模拟一个对象参数

Nsubstitute: Mocking an object Parameter for Unit Testing

我对 Nsubstitute 和单元测试还很陌生。 我知道在单元测试中,您不关心任何其他依赖项。因此,为了应用此规则,我们模拟了单位。

我有这个要测试的示例代码,其中一个方法有一个对象参数:

class dependency {
  public int A;
  public dependency() {
    // algorithms going on ...
    A = algorithm_output;
  }
}

class toTest {
  public int Xa;
  public void Foo(dependency dep_input){
    Xa = dep_input.A;
    // Xa will be used in an algorithm ...
  }
}

我正在考虑模拟构造函数,但我不知道如何在 Nsubstitute 中进行模拟。 那么最终,我将如何测试它?

评论太长没法添加,所以补充一下: 如果你想测试 Foo 你不需要模拟 ctor 但 dep_input。例如,如果您使用 Moq。但是你也可以使用存根

public interface IDependency
{
    int A { get; }
}

public class Dependency : IDependency
{
    public int A { get; private set; }

    public Dependency()
    {
        // algorithms going on ...
        A = algorithm_output();
    }

    private static int algorithm_output()
    {
        return 42;
    }
}

public class ToTest
{
    public int Xa;

    public void Foo(IDependency dep_input)
    {
        Xa = dep_input.A;
        // Xa will be used in an algorithm ...
    }
}

[TestFixture]
public class TestClass
{
    [Test]
    public void TestWithMoq()
    {
        var dependecyMock = new Mock<IDependency>();
        dependecyMock.Setup(d => d.A).Returns(23);

        var toTest = new ToTest();
        toTest.Foo(dependecyMock.Object);

        Assert.AreEqual(23, toTest.Xa);
        dependecyMock.Verify(d => d.A, Times.Once);
    }

    [Test]
    public void TestWithStub()
    {
        var dependecyStub = new DependencyTest();

        var toTest = new ToTest();
        toTest.Foo(dependecyStub);

        Assert.AreEqual(23, toTest.Xa);
    }

    internal class DependencyTest : IDependency
    {
        public int A
        {
            get
            {
                return 23;
            }
        }
    }
}