As you can readily see, although we now have a class definition for Address, there are no methods or properties assigned to it. The SetAddress method of the Employee class has been given a SetAddress method, but it is empty. Although this code will now compile, the test for SetAddress will fail until we add the following line:
this.Address = newAddress;
Now our test cases will green light, but at this stage we haven't really leveraged the true benefit of the mock objects. In fact, we could have used the Address class up to this point. Where mock objects really come into their own, however, is when you need them to behave like the "real" objects they represent, without the need to use true instances of those classes.
To demonstrate this aspect of mock objects, we created a test case for an Employee method called Sync. This method passes the entire Employee object to a SyncServer class which verifies the Employee details and synchronises it with a remote database. The SyncServer class has a method called Receive that is invoked by the Employee.Sync method. Rather than using using a SyncServer object, though, we use a mock object to simulate a SyncServer so that we can be sure we are testing the Sync method in isolation. The test case looks like this.
[Test]
public void EmployeeSyncTest()
{
Mock mockServer = new Dynamic _
Mock(typeof(SyncServer));
Employee emp = new Employee();
mockServer.Expect("Receive", _ emp);
emp.Sync((SyncServer)
_ mockServer.MockInstance);
mockServer.Verify();
}
In order to compile this code, we need a SyncServer class with a Receive method as well as a new Sync method for the Employee class. Our entire application code now looks like this.
namespace Staff
{
public class Employee
{
public string Name;
public Address Address;
public void _SetName(string newName)
{
this.Name = _ newName;
}
public void _ SetAddress(Address newAddress)
{
this.Address = _ newAddress;
}
public void _ Sync(SyncServer newServer)
{
newServer. _ Receive(this);
}
}
public class Address{}
public class SyncServer
{
virtual public void _ Receive(Employee newEmployee){}
}
}