简体   繁体   中英

Nsubstitute: Mocking an object Parameter for Unit Testing

I am fairly new to Nsubstitute and unit testing. I know that in unit testing, you don't care about any other dependencies. So in order for this rule to be applied we mock units.

I have this example to be tested code where a method has an object parameter:

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 ...
  }
}

I was thinking of mocking the constructor but I could not figure out how in Nsubstitute. So ultimately, how would I test this?

I can not add a comment because it is too long, so I add an answer: if you want to test Foo you do not need to mock the ctor but dep_input . For example if you use Moq . But you can also use a stub

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;
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM