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
{
}
}