Archive for the ‘NUnit’ Category

Unit testing with Mock Objects

Friday, February 27th, 2009

In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A developer creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to simulate the dynamic behavior of a human in vehicle impacts.

We use Mock object for NUnit testing if we have 2, 3 or more layer architecture.
In programming terms mock objects are objects that “imitate” some other objects, claiming to have the same attributes, methods etc. like the original.

Rhino Mocks allows you to easily create mock objects and setup a wide range of expectations on them using strongly typed notation instead of compiler-opaque strings.

To mock an object, its class MUST implement an interface.

Public class Car : ICar
{
  public int StartEngine();
  …
  // More methods to be implemented
}
MockRepository mockRepository = new MockRepository();

MyCar = mockRepository.CreateMock<ICar>();

Here is the scenario and source code in C# for demonstration.

We have one solution and 2 projects, representing 2 layers.
Project: DataLayer which gets some information from xml file, database or some other web service, …
DataLayer project has one class: PersonDAL.

using System;
using System.Collections.Generic;
using System.Text;

namespace DataLayer
{
    public class PersonDAL
    {
        private string _name;
        private string _id;
        private List
 lista = new List
();

        public PersonDAL(string name, string id)
        {
            _name = name;
            _id = id;
        }

        public List
 CreateList()
        {

            lista.Add(new PersonDAL("Peter", "1"));
            lista.Add(new PersonDAL("George", "2"));
            lista.Add(new PersonDAL("Michael", "3"));

            return lista;
        }

        public PersonDAL GetPersonByID(string id)
        {
            PersonDAL result = new PersonDAL("", "");
            result = null;

            foreach (PersonDAL person in lista)
            {
                if (person.ID == id)
                {
                    result = person;
                    break;
                }
            }
            return result;
        }

        public string ID
        {
            get { return _id; }
        }
        public string Name
        {
            get { return _name; }
        }

    }
}

it is a simple class which gets data from some resource. In this case, data are hardcoded but never mind.
The other project is BusinessLayer, it represents some business logic. It is Layer 2.
Person class:

using System;
using System.Collections.Generic;
using System.Text;

using DataLayer;

namespace BusinessLayer
{
    public class Person
    {
        public string _id;
        public string _name;  

        public Person(string id, string name)
        {
            _id = id;
            _name = name;
        }

    }
}

interface IPersonService:

using System;
using System.Collections.Generic;
using System.Text;

namespace BusinessLayer
{
    public interface IPersonService
    {
        List
 GetPersons();

        Person GetPersonByID(string id);
    }
}

and PersonService class:

using System;
using System.Collections.Generic;
using System.Text;

namespace BusinessLayer
{
    public class PersonService : IPersonService
    {

        DataLayer.PersonDAL person = new DataLayer.PersonDAL("", "");        

        public List
 GetPersons()
        {
            List
 list = new List
();

            foreach (DataLayer.PersonDAL  objPerson in person.CreateList())
            {
                list.Add(new Person(objPerson.ID, objPerson.Name));
            }

            return list;
        }

        public Person GetPersonByID(string id)
        {
            return new Person(person.GetPersonByID(id).ID,person.GetPersonByID(id).Name);
        }
    }
}

Ok, that is part of some huge application. Let’s code some Unit test here. Supose we do not have data resource at this moment and we can not test this with real data. We must fake it.
So, create new project, type of Class Library into this solution and call it: Test
Add references for both projects and references for NUnit.Framework and
Rhino.Mocks. This project for now has only one class. We use it for testing.
PersonServiceTest class:

 using System;
using System.Collections.Generic;
using NUnit.Framework;
using Rhino.Mocks;

using BusinessLayer;
using DataLayer;

[TestFixture]
public class PersonServiceTest
{

    [SetUp]
    public void TestInit()
    {

    }

    [Test]
    public void Test()
    {
        MockRepository mockRepository = new MockRepository();
        IPersonService personRepository = mockRepository.CreateMock();

        Person mockPerson = new Person("1", "Milan");
        Person objPerson;

        Expect.Call(personRepository.GetPersonByID("1")).Return(mockPerson);

        mockRepository.ReplayAll();

        objPerson = personRepository.GetPersonByID("1");
        Assert.AreEqual(objPerson._id, mockPerson._id);
    }
}

NUnit testing

Friday, February 6th, 2009

What Is Unit test?

A unit test verifies that a function or set of functions meet the requirements.  Unit tests inspect both black boxes or white boxes. NUnitis a unit-testing framework for all .Net languages.
Here is an example. Let’s take a look this class:

namespace Bank
{
    public class Account
    {
        private float balance;

        public void Deposit(float amount)
        {
            balance += amount;
        }
        public void Withdraw(float amount)
        {
            balance -= amount;
        }
        public void TransferFunds(Account destination, float amount)
        {
            destination.Deposit(amount);
            Withdraw(amount);

        }
        public float Balance
        {
            get { return balance; }
        }
    }
}

for this class we make corresponding unit test class like this:

using NUnit.Framework;
using Bank;

namespace Test
{
    [TestFixture]
    public class AccountTests
    {
        [Test]
        public void TestTransferFunds()
        {
            Account source = new Account();
            source.Deposit(200.00F);
            Account destination = new Account();
            destination.Deposit(150.00F);

            source.TransferFunds(destination, 100.00F);

            //Here are assertions
            //we check actual value with expected value
            Assert.AreEqual(250.00F, destination.Balance);
            Assert.AreEqual(100.00F, source.Balance);

        }
  }
}

Assertions are central part of unit testing in any of the xUnit frameworks. NUnit provides a rich set of assertions as static methods of the Assert class.
Example:
Assert.AreEqual( int expected, int actual );
There are:

  • StringAssert
  • CollectionAssert
  • FileAssert

From version 2.0 on, NUnit has used custom attributes.
All NUnit attributes are contained in the NUnit.Framework namespace. Each source file that contains tests must include a using statement for that namespace and the project must reference the framework assembly, nunit.framework.dll.

SetUpFixture Attribute

This is the attribute that marks a class that contains the one-time setup or teardown methods for all the test fixtures under a given namespace. The class may contain at most one method marked with the SetUpAttribute and one method marked with the TearDownAttribute.
Example:

[SetUpFixture]
public class MySetUpClass
{
  [SetUp]
  RunBeforeAnyTests()
  {
    // ...
  } 

  [TearDown]
  RunAfterAnyTests()
  {
    // ...
  }
}

Test Attribute (NUnit 2.0)

The Test attribute marks a specific method inside a class that has already been marked as a TestFixture, as a test method. The signature for a test method is defined as follows:
public void MethodName()

Example:

[Test]
public void Add()
{
	 /* ... */
}

SetUpAttribute

This attribute is used inside a TestFixture to provide a common set of functions that are performed just before each test method is called. A TestFixture can have only one SetUp method. If more than one is defined the TestFixture will compile successfully, but its tests will not run.

Example:

[TestFixture]
public class SuccessTests
{
  [SetUp]
  public void Init()
  {
 	/* ... */
  }
}

TearDownAttribute

This attribute is used inside a TestFixture to provide a common set of functions that are performed after each test method is run. A TestFixture can have only one TearDown method. If more than one is defined the TestFixture will compile successfully, but its tests will not run.
Example:

  [TestFixture]
  public class SuccessTests
  {
    [SetUp]
    public void Init()
    {
	/* ... */
    } 

    [TearDown]
    public void Dispose()
     {
	 /* ... */
     } 

     [Test]
     public void Add()
    {
        /* ... */

    }
}

At the end I want to tell you about ExpectedException Attribute.
We use it when we want to test some exception.
This is the way to specify that the execution of a test will throw an exception.

Example:

  [ExpectedException( typeof( ArgumentException ) )]
  public void TestMethod()
  {
 	...
  }

  [ExpectedException( typeof( ArgumentException ), ExpectedMessage="expected message" )]
  public void TestMethod()
  {
 	...
  }
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in