International Developer Logo Last Updated 27.08.08 at 11.48
On Sale
This months front cover, click to see the table of contents.
Subscribe
 
TUTORIALS

Using Mock Objects in Test Driven .NET Development


Neil Kidd   01.11.05


Mocking simple objects with NMock
To install NMock, simply extract the DLL to the NUnit BIN directory (or other suitable location) and add it to the project's references. Adding another test case to the EmployeeTest class, we have used an NMock DynamicMock object to emulate the yet-to-be-created Address class. Each instance of the Employee class will have an Address object assigned to it and our mock object allows us to test this without involving the actual Address class itself. Subsequently, our new test case looks like this.

[Test]
public void EmployeeSetAddressTest()
{
 Mock mockAddress = new Dynamic _
Mock(typeof(Address));
 Employee emp = new Employee();
 emp.SetAddress((Address)
mockAddress.MockInstance);
 Assert.AreSame(emp.Address,(Address)
mockAddress.MockInstance);
 mockAddress.Verify();
}

This code creates a mockAddress object and passes it to the SetAddress method of the Employee class. Then we assert that the Address property of the Employee is identical to the mock object before verifying that the object was only used once. This code, by definition, will not compile until we add the bare minimum of application code as shown below.

namespace Staff
{
 public class Employee
 {
  public string Name;
  public Address Address;
  public void _ SetName(string newName)
  {
   this.Name = newName;
  }
  public void _SetAddress(Address newAddress)
  {
   //assignment _ code to go here
  }
 }
 public class Address
 {
 }
}




   Previous Page  1 2 3 4 5 6 7 8 9 10 ... Next Page   

HAVE YOUR SAY
This article is rated  Rate this article