Moq Quick Reference for Rhino Mocks Users

Behold! A quick reference guide for Rhino Mocks (AAA syntax) users making the switch to Moq.

Rhino MocksMoq
MockRepository.GenerateMock<T>new Mock<T>
MockRepository.GeneratePartialMock<T>new Mock<T> { CallBase = True }
.Stub(…).Return(…)
.Stub(…).WhenCalled(…)
.Stub(…).Do(…)
.Setup(…).Returns(…)
.Expect(…).Return(…)
.Expect(…)
.Setup(…).Returns(…).Verifiable()
.Setup(…).Verifiable()
Arg<T>.Is.AnythingIt.IsAny<T>()
Arg<T>.Matches(…)It.Is<T>(…)
Arg<T>.Is.Equal(foo)It.Is<T>(x => x == foo)
.AssertWasCalled(…).Verify(…)
.AssertWasNotCalled(…).Verify(…, Times.Never)
.VerifyAllExpectations().Verify()

In addition to the syntax translations listed in the table above, a key difference is that you use the instantiated mock object via the mock’s Object property. For example:

var mock = new Mock<SomeClass>();
SomeMethod(mock.Object);

Output Parameters in Argument Constraints with Rhino Mocks… Again!

One of my favorite things about being a blog owner and operator is when I’m looking for something and find that I’ve already answered my own question. This just happened to me as I was trying to re-figure out how to use output parameters with argument constraints with Rhino Mocks.

I found an article on this very topic written by me (thanks, self!), but as I was reading I noticed that I left something important out. So here’s a quick, mini do-over!

Let’s say we need to stub function Bar as it’s defined in the following interface:

public interface IFoo
{
    bool Bar(out string outty);
}

To use an argument constraint with the output argument, I need to do two things. First, I need to use Arg<T>.Out. The second thing–the thing that I failed to mention in my previous post–is that I need to use the Dummy property to make it compile.

Here’s what an example might look like. I stubbed the Bar function to return true and assign the value fake value! to the output argument.

IFoo mockFoo = MockRepository.GenerateMock<IFoo>();
mockFoo(x => x.Bar(out Arg<string>.Out("fake value!").Dummy)).Return(true);

Not too shabby!

Property Behavior in Rhino Mocks and Stubs

A co-worker presented me with a scenario where assigning and accessing a property from a Rhino Mocks stub worked as expected, but changing the stub to a dynamic mock caused the test to fail. This didn’t really seem like a stub-versus-mock question since stubs and dynamic mocks generally function similarly, with the difference being that mocks allow you to verify expectations whereas stubs only allow you to stub return values.

Here’s a simplified version of the problem:

[TestMethod]
public void TestWithStub()
{
    var sampleStub = MockRepository.GenerateStub<ISample>();
    sampleStub.Value = "bar";

    // success!
    Assert.AreEqual("bar", sampleStub.Value);
}

[TestMethod]
public void TestWithMock()
{
    var sampleMock = MockRepository.GenerateMock<ISample>();
    sampleMock.Value = "foo";

    // fail!
    Assert.AreEqual("foo", sampleMock.Value);
}

I’ve seen guidance online that suggests this is the correct way to handle stubbed properties. This is primarily what makes the issue confusing to me. However, per the Rhino Mocks 3.3 Quick Reference Guide, the correct way to handle property getters and setters for mocks is to use Expect.Call(foo.Name).Return(“Bob”) and Expect.Call(foo.Name = “Bob”), respectively. The quick reference guide also identifies a way to do “automatic properties” by using the PropertyBehavior method. The PropertyBehavior method allows properties in mocks to function like they do in stubs. The behavior is enabled on stubs be default, which is what causes the out-of-the-box behaviors to be different.

By adding a call to PropertyBehavior, the seemingly-correct sample test above succeeds.

[TestMethod]
public void TestWithMock()
{
    var sampleMock = MockRepository.GenerateMock<ISample>();
    sampleMock.Expect(x => x.Value).PropertyBehavior();
    sampleMock.Value = "foo";

    // success!
    Assert.AreEqual("foo", sampleMock.Value);
}

Note that although we use an Expect method, there is no expectation set when using the PropertyBehavior method. This means that the test will pass even if the property is not used at all. If you need to verify getters and setters, you should use mock.Expect(x => x.Value).Return(“foo”) and mock.Expect(x => x.Value = “bar”).

Output Parameters in Argument Contraints with Rhino Mocks

Today, I was writing tests for a method that had an output parameter in its argument list. With Rhino Mocks, this can be very simple and straightforward. In the cookie-cutter example, you can simply pass in the output parameter the same way you’d pass it to the function.

bool outParam;
var mock = MockRepository.GenerateMock<ISomeInterface>();
mock.Expect(x => x.MethodWithAnOutParam(out outParam));

But, what if you want to use argument constraints? It becomes a little less obvious but still very easy.

var mock = MockRepository.GenerateMock<ISomeInterface>();
bool refParam;
mock.Expect(x => x.MethodWithARefParam(
    Arg<string>.Is.Anything, 
    ref Arg<bool>.Ref(Is.Anything(), true).Dummy));

Note that the value in parentheses is the value that will be assigned to the output parameter passed into the function.

You can use the Ref constraint to similarly deal with ref parameters. Notice that the Ref constraint takes two arguments, though: a Rhino AbstractConstraint and the return value.

var mock = MockRepository.GenerateMock<ISomeInterface>();
bool outParam;
mock.Expect(x => x.MethodWithARefParam(
    Arg<string>.Is.Anything, 
    ref Arg<bool>.Ref(Is.Anything(), true).Dummy));

Ordered Tests with Rhino Mocks AAA Syntax

Before the AAA syntax was introduced, you would create ordered unit tests by wrapping Expect calls in a using block like so:

var mocks = new MockRepository();
using (mocks.Ordered())
{
    // ...
}

However, AAA syntax does not require you to instantiate a MockRepository, so how can we do ordered tests? This can be accomplished by accessing the implied MockRepository via the GetMockRepository method.

var myMock = MockRepository.GenerateMock<IMyInterface>();
using (myMock.GetMockRepository().Ordered())
{
    // ...
}

Here’s a complete example.

[TestMethod]
public void RunTest()
{
    // Arrange
    var target = new Program();
    var mockModel = MockRepository.GeneratePartialMock<MyModel>();
    target.Model = mockModel;

    using (mockModel.GetMockRepository().Ordered())
    {
        mockModel.Expect(x => x.Populate());
        mockModel.Expect(x => x.Save());
    }

    // Act
    target.Run();

    // Assert
    mockModel.VerifyAllExpectations();
}
// This fails
public void Run()
{
    Model.Save();
    Model.Populate();
}

// This passes
public void Run()
{
    Model.Populate();
    Model.Save();
}

Unit Testing Stored Procedure Calls with Rhino Mocks

Database stored procedure calls are one of the trickiest things to unit test, and there are many different approaches that can be taken. My team has run the gamut: test DBs that rollback with each run, no testing for direct data access functions (!), virtual functions w/ partial mocks (see here).

The latest approach that I’ve been using is much more straightforward and feels like a more natural use of Rhino Mocks. Let’s look at some examples of how to test some common database stored procedure tasks. (Note that these examples assume use of the Microsoft Enterprise Library.)

Create a mockable Database

The primary challenge that I’ve found with testing database code is that Microsoft.Practices.EnterpriseLibrary.Data.Database isn’t mock-friendly. However, the other “pieces” such as DbCommand and DbCommandParameterCollection are very easy to work with. So, we can solve the Database problem by creating a simple wrapper (Important! Note that the methods have the virtual keyword, which will allow them to be overridden.):

public class DatabaseWrapper
{
    private Database _database;
    private Database Database
    {
        get { return _database = _database ?? DatabaseFactory.CreateDatabase(); }
        set { _database = value; }
    }

    public virtual DbCommand GetStoredProcCommand(string storedProcedureName)
    {
        return Database.GetStoredProcCommand(storedProcedureName);
    }

    public virtual void DiscoverParameters(DbCommand command)
    {
        Database.DiscoverParameters(command);
    }
}

Executing a stored procedure

Now that we are able to mock the database object, we can write some useful tests. Let’s say you want to execute a stored procedure named “MyStoredProcedure,” and you want to write a test to verify that your code handles an exception thrown when it’s executed. That’s very easy!

Here’s my class with the function I want to test:

public class MyDataAccess
{
    public DatabaseWrapper Database { get; set; }
    public Thingy GetThingy()
    {
        Thingy thingy = null;
        try
        {
            var dbCommand = Database.GetStoredProcCommand("MyStoredProcedure");
            Database.DiscoverParameters(dbCommand);
            var result = dbCommand.ExecuteNonQuery();
            // populate thingy
        }
        catch (Exception ex)
        {
            // handle exception
        }
        return thingy;
    }
}

And here’s my test that will throw an exception when the stored procedure is executed. I create my DatabaseWrapper as a PartialMock, allowing me to override its methods.

[TestMethod]
public void GetThingyHandlesException()
{
    // Arrange
    var target = new MyDataAccess();
    var mockDatabase = MockRepository.GeneratePartialMock<DatabaseWrapper>();
    target.Database = mockDatabase;

    // mock Database
    const string storedProc = "MyStoredProcedure";
    var mockDbCommand = MockRepository.GenerateMock<DbCommand>();
    mockDatabase.Expect(x => x.GetStoredProcCommand(storedProc))
        .Return(mockDbCommand);
    mockDatabase.Expect(x => x.DiscoverParameters(mockDbCommand));
    
    // mock DbCommand
    var ex = new Exception("Oh noes!");
    mockDbCommand.Expect(x => x.ExecuteNonQuery())
        .Throw(ex);

    // Act
    var actual = target.GetThingy();

    // Assert
    mockDatabase.VerifyAllExpectations();
    mockDbCommand.VerifyAllExpectations();
    Assert.IsNull(actual);
}

Setting input parameters

Need to set some input parameters? No problem!

dbCommand.Parameters["@id"].Value = id;

And, in your test, you add this:

var mockParams = MockRepository.GenerateMock<DbParameterCollection>();
var mockParam = MockRepository.GenerateMock<DbParameter>();

mockDbCommand.Expect(x => x.Parameters).Return(mockParams);

mockParams.Expect(x => x["@id"]).Return(mockParam);

const int id = 123;
mockParam.Expect(x => x.Value = id);

mockParams.VerifyAllExpectations();
mockParam.VerifyAllExpectations();

Reading output parameters

How about output parameters?

thingy.Value = dbCommand.Parameters["@Value"].Value as string;

Add the additional mocks and assertions:

var mockOutParam = MockRepository.GenerateMock<DbParameter>();

mockParams.Expect(x => x["@Value"]).Return(mockOutParam);

const string value = "MyValue";
mockOutParam.Expect(x => x.Value).Return(value);

mockParams.VerifyAllExpectations();
mockOutParam.VerifyAllExpectations();
Assert.AreEqual(value, actual.Value);

Working with sets of parameters

When you have more than a few parameters to work with, the unit test code can get quite lengthy. I like to keep it clean by extracting the duplicated logic into a separate function, like so:

var paramsToVerify = new List<DbParameter>();
mockParams.Expect(x => x["@whammyparammy"])
    .Return(MockParameter<int>(paramsToVerify));

My function allows you to specify and verify the type of each parameter, but you could easily modify it to expect a specific value.

private static DbParameter MockParameter<T>(List<DbParameter> paramsCollection)
{
    // set Expect with Arg<T>.Is.TypeOf to force the specific type
    var mockParam = MockRepository.GenerateMock<DbParameter>();
    mockParam.Expect(x => x.Value = Arg<T>.Is.TypeOf);

    if (paramsCollection != null)
        paramsCollection.Add(mockParam);

    return mockParam;
}

I keep the parameters in a list so I can verify them during my assertions.

paramsToVerify.ForEach(x => x.VerifyAllExpectations());

Testing Hard-to-Test Code with Rhino Mocks

One of the most common gripes that I hear about getting started with unit testing is that the code isn’t testable or it doesn’t have a testable design. People will make claims like, “We need X hours to make the project testable before we can start writing tests.” Well, I don’t buy into that. There are techniques that you can employ to extract the pieces of code you’re modifying into little, testable nuggets that have nothing to do with the rest of the not-so-test-friendly project. I’m going to cover two of my favorite, most-commonly used techniques in this post.

Extract the code to be tested.

This is a pretty straightforward solution to a not-so-obvious problem. The most common scenario that I’ve seen for this technique is the “monster function.” I’m sure you’ve seen this before. It’s the 1000-line function that contains all the logic for the module or application you’re modifying. This is a classic hard-to-test situation because, at first glance, it seems like you need to set up everything necessary to complete the entire process in order to do any sort of unit testing.

To transform this mess into an unit testing masterpiece, you just need to do what nobody before you thought of: create a new function. Your new function can do whatever you need it to do. It can accept inputs. It can return outputs. And, it can do it all in a testable manner! So, make your function, test the hell out of it, then call your function from the appropriate place in the main function. Congratulations–you just made a unit tested change to a previously non-testable function.

Extract the code to be avoided.

The second scenario is a little more difficult, and the solution is a little less obvious. I use this technique when I’m dealing with external dependencies that aren’t enough to warrant an entire interface or when I’m working with tricky internal dependencies. Let’s look at an example. Consider the following function:

public class HardToTest
{
    public void ProcessFile()
    {
        string contents;
        using (var fs = new FileStream(@"c:\data.xml", FileMode.Open))
        {
            var sr = new StreamReader(fs);
            contents = sr.ReadToEnd();
        }
        // Do something interesting with file contents
    }
}

When sitting down to write a unit test for this function, you might be tempted to create a “data.xml” file in the root directory of the C drive during TestInitialize. That would probably result in a passing unit test on your machine, but please, don’t do that. You can trust that the FileStream and StreamReader objects will do their jobs correctly, so let’s just take them out of the equation for our unit testing. With a quick refactor, we end up with something like this:

public class HardToTest
{
    public void ProcessFile()
    {
        string contents = GetFileContents();
        // Do something interesting with file contents
    }
    
    internal protected virtual string GetFileContents()
    {
        using (var fs = new FileStream(@"c:\data.xml", FileMode.Open))
        {
            var sr = new StreamReader(fs);
            return sr.ReadToEnd();
        }
    }
}

Ok, great! Now, here’s where it gets fun. We can write a test for this function by mocking just the function we’re trying to avoid. Check it out:

[TestMethod()]
public void ProcessFileTest()
{
    HardToTest target = MockRepository.GeneratePartialMock();
    target.Expect(x => x.GetFileContents()).Return("File contents!");
    target.ProcessFile();
    target.VerifyAllExpectations();
}

Because we made our GetFileContents function virtual, the generated mock class can override its functionality. The Partial Mocks gives us this functionality; if the function were not overridden, it would be called as-is and would try to read from the hard-coded file path.

You could stick with this same approach to handle different scenarios that might arise in the isolated code. For instance, what would happen if the file did not exist? You would expect the isolated code to throw a System.IO.FileNotFoundException, right? Well, let’s test that!

[TestMethod]
[ExpectedException(typeof(System.IO.FileNotFoundException))]
public void ProcessFile_ThrowsFileNotFoundException()
{
    HardToTest target = MockRepository.GeneratePartialMock();
    target.Expect(x => x.GetFileContents()).Throw(
        new System.IO.FileNotFoundException());
    target.ProcessFile();
}

Some additional notes about this solution:

  • The function must be internal (see next note) protected (prevents calling of the function while setting expectation) virtual (allows function to be overridden).
  • The target project must expose its internals to the test project. This can be done by adding the “[assembly: InternalsVisibleTo(“YourTestProjectName”)]” attribute to the target project’s assembly.info file. You can read more about this attribute here.