Mocking in Unit Tests
page 1 of 8
Published: 31 May 2007
Abstract
In this article Brian shows you a simple way to mock in your applications, followed by a demonstration of the TypeMock framework, a tool that greatly increases what you can test in your applications.
by Brian Mains
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 40605/ 72

Introduction

Unit testing adds a new capability to application development testing. The ability to execute code that ensures the design, logic, and functionality of an application is the key to developing successful, bug-free software. However, there are times where unit testing is not enough. This is especially true when the properties/methods you really need to test are declared private, protected, or internal/friend.

How do you compensate for that?  Inheritance can work; for instance, your unit test can inherit from the class that defines protected methods, and validate these internal methods in that manner.  That is useful, but not always efficient.  In addition, what about internal/friend and private methods/properties?

Another option is reflection.  Reflection has the capabilities to peek underneath an object, inspect its metadata, and through that get/set properties or invoke methods that you normally could not access.  This is one of the means we will look at.

Secondly, there is the concept of mocking/stubbing classes in an application.  Mocking is the art of inspecting an object's behavior to ensure that it makes all of the correct assignments or operations.  It even can be used to test how the code handles if a different value is returned or if an exception is thrown.  Martin Fowler calls this process "behavior verification," which is exactly what is done with mocks.

From this, there are several ways to do this.  The first that I will show you is to create your own way to test the logic.  I created a set of components to do this in my Nucleo Framework to test the logic.  By inserting the logic you would like to implement directly into a test, you can use these objects to mock the return value.  It is not illustrating the full value of mocking, as we shall see in the following example using the TypeMock library, a freely-available library that intercepts calls to your method and allows you to verify/control the processing that goes on in a method.  We shall see more examples below.


View Entire Article

User Comments

No comments posted yet.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2017 ASPAlliance.com  |  Page Processed at 2017-04-23 9:50:34 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search