For the past eight(8) years Schalk Neethling has been working as a freelance developer under the pseudo of Volume4 and is now the president of Overt Strategy Consulting. During this period he has completed over 300 projects ranging from full web application development to complete branding. As president and lead developer of Overt Strategy Consulting, Schalk Neethling and his team has released a 100% Java standards based content management system called AlliedBridge and business document exchange and review system, called Doc-Central. Schalk Neethling is also actively involved on a daily basis in the open source, web standards and accessibility areas and is a current active member of the Web Standards Group. Schalk is also the co-founder and president of the non-profit The South Web Standards and Accessibility Group, which aims to actively educate and raise awareness of web standards and accessibility to both the developer society as well as business large and small. Schalk also has a long relationship with DZone and is currently zone leader for both the web builder, css.dzone.com, as well as the .NET zone, dotnet.dzone.com, and you can find a lot of his writing there as well as on his blog located at schalkneethling.alliedbridge.com. Schalk is constantly expanding on his knowledge of various aspects of technology and loves to stay in touch with the latest happenings. For Schalk web development and the internet is not just a job, it is a love, a passion and a life style. Schalk has posted 173 posts at DZone. View Full User Profile

A Simple Manual Mock Example

10.13.2008
| 20839 views |
  • submit to reddit

Creating and using a mock object is semantically very much like using a stub, except that a mock will do a little more than a stub - it will save the history of communication so that it can later be verified. Let's add a new requirement to our LogAnalyzer class. It will have to interact with an external web service that will receive an error message whenever the LogAnalyzer encounters a filename whose length is not too long.

Unfortunately, the web service we'd like to test against is still not fully functional, and even if it were, it would have taken too long to use it as part of our tests. Because of that, we'll refactor our design and create a new interface that we can use to later create a mock object of. The interface will have the methods we will need to call on our web service, and nothing else.

 

 

 

Figure 1 shows how the test will work with our MockWebService.

First off, let's extract a simple interface that we can use in our code under test, instead of talking directly to the web service.

public interface IWebService
{
void LogError(string message);
}

This interface will serve us when we want to create stubs as well as mocks, without needing to have an external dependency on a project we have no control of. Next, we'll create the mock object itself. It may look like a stub, but it contains one little bit of extra code that makes it a mock object.

public class MockService:IWebService
{
public string LastError;
public void LogError(string message)
{
LastError = message;
}
}

Our mock implements an interface just like a stub, but saves some state for later, so that our test can then assert and verify that our mock was called correctly. Listing 1 shows what the test might look like:

Listing 1: The log analyzer under test actually calls our mock object, which holds on to the string that is passed into the implemented method, and later asserted in the test.

[Test]
public void Analyze_TooShortFileName_CallsWebService()
{
MockService mockService = new MockService();
LogAnalyzer log = new LogAnalyzer(mockService);
string tooShortFileName="abc.ext";
log.Analyze(tooShortFileName);
Assert.AreEqual("Filename too short:abc.ext", |#1
mockService.LastError); |#1
}
public class LogAnalyzer
{
private IWebService service;
public LogAnalyzer(IWebService service)
{
this.service = service;
}
public void Analyze(string fileName)
{
if(fileName.Length<8)
{
service.LogError("Filename too short:" |#2
+ fileName); |#2
}
}
}

Annotation #1:
The assert is done against the mock service, and not against the class under test
Annotation #2:
The method part we're going to test

Notice how the assert is performed against the mock object, and not against the LogAnalyzer class. That's because we are testing the interaction between LogAnalyzer and the web service. We still use the same dependency injection techniques, but this time the stub also makes or breaks the test. That's why it's a mock object. Also notice that we are not writing the tests directly inside the mock object code. There are several reasons for this.

We'd like to be able to re-use the mock object in other test cases, with other asserts on the message. If the assert is found inside the mock object, whoever is reading the test will have no idea what we are asserting. We will be hiding essential information from the test code, which hinders the readability and maintainability aspect of the test.

In many scenarios in your tests, you might find that you need to replace more than one object for the test to be able to work, which involves combining mocks and stubs.

This article is taken from the book The Art of Unit Testing. As part of a chapter on interactive testing using mock objects, this segment shows how to create and use a mock object and helps differentiate mock objects from stubs.

Published at DZone with permission of its author, Schalk Neethling.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)