All posts by scott

Introduction to Rhino Mocks

[image via Brian Schroer]
Because mocking objects is awesome, here is a quick introduction to Rhino Mocks so that we can use it in any C# code.

What is a mock object?

The mock object is a very light weight object where you can simply define what to return when a given method is called with a given parameter. You may at some point want to write a unit test on an object that depends on another class. To avoid this dependecy, you mock out that class and replace it with a mock object. So, for example, if I’m testing an aggregate class:

// combines a list of numbers using a given operator.
// e.g. if your operator is addition, and you pass 2,3,4 to the aggregate method,
// it will return 2+3+4=9
class Aggregator
{
    Aggregator(IOperation op) {...}
    double Aggregate(out string text, params double[] numbers) {...}
}
// an operator such as addition or subtraction or a random number generator.
interface IOperator
{
    string DisplayText {get; set;}
    double Operate(double a, double b);
}

Mocks give you the freedom from depending on an operator to perform correctly in order to have your unit tests for the aggregator class to pass. Continue reading Introduction to Rhino Mocks