Typemock back to basics: Faking “Future” Instances

Guest post by Lior Friedman. This is a part of a series called “Back to basics” of unit testing.

One of the best things about the Isolator is that it can fake instances which are created inside the production code. This kind of faking is called "faking a future instance".

Lets see an example how this can be used. Here’s my production code that I need to test:

public class Client
{
Server m_Server = null;

public Client(IPAddress addr)
{
m_Server = new Server();
m_Server.Connect(addr);
}

public int SendInfo(string message)
{
m_Server.Send(message);
string answer = m_Server.Recieve();
if (answer != "OK")
{
throw new ApplicationException
("Failed To Communicate");
}
return message.Length;
}
}

The method I want to test is SendInfo, and a simple test would be to make sure that when sending is successful, the actual number bytes sent is returned by it.

The tricky bit resides in the Constructor of the Client class . As you can see, the client creates his own server and connect to it based on the address given by the user.

Here’s the test code:

[TestMethod()]
public void SendInfo_SuccesfulSend_SendsAllBytes()
{
//creating the fake
Server fakeServer = Isolate.Fake.Instance<Server>();
//setting behavior
Isolate.WhenCalled(() => fakeServer.Recieve()).
WillReturn("OK");
//When the next Server is created, swap it with fakeServer
Isolate.Swap.NextInstance<Server>().With(fakeServer);

var address = new IPAddress(
new byte[] {192,168,0,9}
);
string message = "Hello Server";

Client target = new Client(address);
int actual = target.SendInfo(message);

Assert.AreEqual(message.Length, actual);
}

Specifically important is this line:

//When the next Server is created, swap it with fakeServer
Isolate.Swap.NextInstance<Server>().With(fakeServer);

After I’ve created the fakeServer and set the desired behavior, this command tells Isolator to swap the next created instance with the fakeServer I’ve created. That is, the next time someone will will create an instance of the Server Class (as done in the client constructor), Instead of getting a real server he will get the fake instance I specified in the "With" segment.

By the way, in the “With” clause, I can supply a fake or a real object. Quite simple isn’t it?

Lior Friedman

TOP