Saturday, September 19, 2015

NSubstitute: For those who hate lambdas :)



NSubstitute is another mocking framework which performs similar purpose to Moq / FAkeItEasy and many more. The Good part of NSubstitute is , it avoids lambda expression in syntax where Moq , FakeItEasy family uses it.

Basically NSubstitute framework is best fit for TDD but you may use this at any point of unit testing. Let’s assume that here is our code which need to be test using NSubstitute.

public interface IService
{
    string MessageSend();
}

public class Service : IService
{
    IService _tmpService;
    public Service(IService service)
    {
        _tmpService = service;
    }

    public string MessageSend()
    {
        return "message";
    }
}

The code snippet is very simple, we are just injecting IService to Service class. Here is code for unit test.

[TestClass]
    public class UnitTestClass
    {
        [TestMethod]
        public void Test_Function()
        {
            //Arrange
            var substitute = Substitute.For<IService>();

            //Act
            substitute.MessageSend().Returns("fake data");

            //Assert
            Assert.AreEqual("fake data", substitute.MessageSend());

        }
    }

We are seeing that there is no lambda expression in code and very clean compare to other framework.

No comments:

Post a Comment