Check out myAngular article series with live demos

How to Mock with NSubstitute

Torgeir "Tor" Helgevold
- JavaScript Developer and Blogger
Published: Sun May 10 2015

There are several great mocking frameworks available for .Net, but NSubstitute stands out because of its simple and elegant syntax. Perhaps the biggest benefit is how easy it is to integrate mocked objects with the code under test. There is no need for framework specific bootstrapping, or extra properties to access the objects you are mocking.

Bellow is an example of a simple unit test using NSubstitute.

    public interface ICustomerRepository
    {
        Customer GetCustomerById(int customerId);
    }

    public class CustomerService
    {
        private ICustomerRepository _customerRepository;

        public CustomerService(ICustomerRepository customerRepository)
        {
            this._customerRepository = customerRepository;
        }

        public string GetFullName(int customerId)
        {
            Customer customer = this._customerRepository.GetCustomerById(customerId);
            return string.Format("{0} {1}",customer.FirstName,customer.LastName);
        }
    }

    [TestClass]
    public class CustomerServiceTests
    {
        [TestMethod]
        public void Will_Return_Customer_FullName()
        {
            ICustomerRepository customerRepository = Substitute.For<ICustomerRepository>();
            customerRepository.GetCustomerById(1).Returns(new Customer() { FirstName = "John", LastName = "Smith" });

            CustomerService customerService = new CustomerService(customerRepository);

            string fullName = customerService.GetFullName(1);

            Assert.AreEqual("John Smith", fullName);
        }
    }  

If you liked this article, it to your friends.

I also invite you to follow me on twitter