Home Blog .NET Testing with nUnit and MOQ on Visual Studio 2013
Testing with nUnit and MOQ on Visual Studio 2013
.NET
Written by Dicky   
Friday, 22 August 2014 09:34
AddThis Social Bookmark Button

During software development, my testing is limited using NUnit. I want to use MOQ during my testing so it's not dependent on database when getting the object values. During my first try, it looks like a great framework and easy to use.

With Visual Studio 2013, Test Explorer is built-in within the IDE, it would be under Test - Windows - Test Explorer menu item. To install NUnit and get it working with Test Explorer, you need to install the NUnit Test Adapter from Visual Studio Gallery. If you simply install it from the NuGet package then you won't have nUnit.Runners built-in into the Test Explorer by going to Test .

You can follow this article to build a sample program, along with Test Fixture and MOQ implementation. It's pretty straight forward, I even modify the testing to do additional testing and separate the initialization within the [SetUp] and Init() method. Here's a sample code:

[TestFixture]
public class PeopleTests
{
    IRepository<Person> _personRepository;

    [SetUp]
    public void Init()
    {
        var repository = new Mock<IRepository<Person>>();
        var data = new List<Person>
        {
            new Person {FirstName = "John", LastName = "Doe"},
            new Person {FirstName = "Jane", LastName = "Doe"},
            new Person {FirstName = "John", LastName = "Smith"},
            new Person {FirstName = "Matthew", LastName = "MacDonald"},
            new Person {FirstName = "Andrew", LastName = "MacDonald"}
        };
        repository.Setup(r => r.GetAll()).Returns(data);
        repository.Setup(r => r.GetName()).Returns("woot");
        _personRepository = repository.Object;
    }

    [Test]
    public void Should_Return_Two_Persons_With_FirstName_John()
    {
        // Setup
        //var repository = new PersonRepository();
        //var people = new People(repository);
        var people = new People(_personRepository);
        // Action
        var persons = people.Query(p => p.FirstName == "John");

        // Verify the result
        Assert.AreEqual(persons.Count(), 2, "Should return 2 persons with first name John.");
    }

    [Test]
    public void Should_Return_Woot()
    {
        var people = new People(_personRepository);

        // Verify the result
        Assert.AreEqual(people.GetName(), "woot", "Should return \"woot\"");
    }

    [Test]
    public void Should_Return_Two_Persons_With_LastName_MacDonald()
    {
        var people = new People(_personRepository);

        // Action
        var persons = people.Query(p => p.LastName == "MacDonald");

        // Verify the result
        Assert.AreEqual(persons.Count(), 2, "Should return 2 persons with last name MacDonald.");
    }
}