A while back I wrote a Quick Guide to Using Rhino.Mocks and in last week's post, I gave an overview of Moq for Rhino.Mocks Users. While Moq seems to be the current front runner as a Rhino.Mocks replacement, there's another player in town with NSubstitute. So in the same vane as my Moq post, I'm providing a guide to help people make the transition (or at least help with a review) from Rhino.Mocks to NSubstitue.

The format of this post will follow that of the others to help with cross-referencing between them.

Overall, I'm not a big fan of NSubstitute's syntax, as it looks too similar to just calls to the methods themselves, which:

makes it harder to understand, as the reader must know which calls are setting up stubs and which are real calls.

makes it much more likely you'll accidentally do the wrong thing and call a real method.

Now, if you're only mocking interfaces, then this wouldn't be an issue -- but rarely do I find a codebase that allows everything to be an interface.

Generating Different Mock Types

By default, NSubstitue's .For<T> method generates something close to a Dynamic mock -- that is, if you don't explicitly provide a return value, it will return the default value for the data type of the return value if it's a value type (0 for numbers, false for bools, empty string for string), but for object types, it's a bit more complicated. From their documentation:

A pure virtual class is defined as one with all its public methods and properties defined as virtual or abstract and with a default, parameterless constructor defined as public or protected.

So it won't return null in those cases. Instead, it creates a new mock of the return type. Otherwise, it will return null.

Be careful, thought -- if you are using a real class (not an interface), it will call the underlying methods if they aren't virtual.

That said, there is the concept of a partial mock using .ForPartsOf<T> -- that is, a mock that can use the underlying object's implementation. However, to prevent calling the real methods for the methods you do want to mock, you must use the syntax described in the Advanced Argument Constraints section below.

Passing Constructor Arguments

If you need to pass arguments to the constructor of the class you're trying to mock, there are overloads to allow you to do that.

Rhino.Mocks

NSubstitute

IFoo mock = MockRepository.GenerateMock<SomeClass>(param1, param2);

Substitue.ForPartsOf<SomeClass>()(param1, param2);

Stubs vs Mocks (or not)

The syntax for NSubstitute is a little different than the others. In most cases, there's not an explicit method you call to create the mock/stub -- rather, you basically call the method you want to create a substitue for. Also, there's no distinction between a mock and a stub -- they're all just substitutions. But since they don't create _expectations_, I would classify them as stubs.

You use the .Returns() method to setup the stub. Note that you can provide multiple values to .Returns() which will set up a chain of calls, like this: .Returns(valueForFirstCall, valueForSecondCall, valueForThirdCall). This works for methods and properties.

Unlike Rhino.Mocks, however, if some other code sets the property value to something else, NSubstitute's stub will return the new value, not the value you stipulated in your stub. In other words, NSubstitue's properties will act like regular properties, and your stub just sets an initial value.

Verifying expectations

Since you're not creating expectations with NSubstitute, there are no mass validation options. Instead, you need to check each stub (which, being more explicit, is probably the better route anyway).

Note that for the getter, you must set a variable to the return value to prevent a compiler error.

The WithAnyArgs versions will ignore whatever parameters (for methods) or set values (for properties) you use in your check and will verify against any inputs.

Advanced Argument Constraints

Both frameworks provide ways to put advanced constraints on the arguments that trigger a mock. Below are examples -- you'll need to consult the framework documentation for the full list of available constraints.

Testing Non-Public Members

With Rhino.Mocks, you can’t mock private or internal members, but you can mock internal members if you add an InternalsVisibleTo attribute for the Castle dynamic proxy assembly. NSubstitute also uses the same proxy, so you'll still need to add the attribute. See the Moq Quickstart Guide for details on how to do this.

This post hopes to serve as a guide for people making the transition from Rhino.Mocks to Moq.

One big difference between Rhino.Mocks and Moq is what gets returned when you generate the mock and how you operate against it. With Rhino.Mocks, the MockRepository returns to you an instance of the type you're mocking and you apply the mock operators (.Stub(), .Expect(), .VerifyAllExpectations(), etc) directly to that mocked object. Moq, on the other hand, creates a wrapper object that contains a reference to the
mocked type.

So in this example, I'm creating an mock of IFoo. For Rhino.Mocks, I get back an IFoo object, but Moq returns a Mock<IFoo> and to get the IFoo object, you access it with the .Object property.

Generating Different Mock Types

A strict mock requires you to provide alternate implementations for each method/property that is used on the mock. If any methods/properties are used which you have not provided implementations for, an exception will be thrown.

Dynamic Mock

With a dynamic mock, any methods/properties which are called by your tests for which you have not provided an implementation will return the default value for the data type of the return value. In other words, you'll get back a 0 for number types, false for Booleans and a null for any object types.

Partial Mock

A partial mock will use the underlying object's implementation if you don't provide an alternate implementation. So if you're only wanting to replace some of the functionality (or properties), and keep the rest, you'll want to use this. For example, if you only want to override the method IsDatabaseActive(), and leave the rest of the class as-is, you'll want to use a partial mock and only provide an alternate implementation for IsDatabaseActive().

Note that Moq uses the term "Loose Mock" for the Dynamic mock concept. Both frameworks default to Dynamic\Loose mocks.

I'm not a fan of this syntax, because it lets you mix methods in ways that don't make sense, like a strict mock that calls it's base methods: Mock<IFoo> mockWrapper = new Moq.Mock<IFoo>(MockBehavior.Strict) { CallBase = true };. It's not clear what will happen in this scenario if I call a method I haven't explicitly mocked, because using two different inputs (a constructor argument and a property) to represent competing concepts leads to confusion. That said, I can tell you what happens: The Strict setting takes precedent and a runtime exception is thrown:

Moq.MockException : Class1.GetFoo() invocation failed with mock behavior Strict.
All invocations on the mock must have a corresponding setup.

Passing Constructor Arguments

If you need to pass arguments to the constructor of the class you're trying to mock, there are overloads to allow you to do that.

Stubs vs Mocks

A stub is simply an alternate implementation. A mock, however, is more than that. A mock sets up an expectation that

A specific method will be called

It will be called with the provided inputs

It will return the provided results

In Rhino.Mocks, you used the .Stub() and .Expect() extension methods to generate your stubs and mocks directly off your mock object. Moq, on the other hand, uses the .Setup() method on the wrapper object to create both. By default, it will create a stub (no expectation), but if you add Verifiable(), it will generate the expectations (thus, becoming a mock).

For both frameworks, you can explicitly verify stubs, but if you want to do mass verification, you must create the expectations up front.

For Methods:

Rhino.Mocks

Moq

Stub

mock.Stub(x => x.SomeMethod()).Return(true);

mockWrapper.Setup(x => x.SomeMethod()).Returns(true);

Mock

mock.Expect(x => x.SomeMethod()).Return(true);

mockWrapper.Setup(x => x.SomeMethod()).Returns(true).Verifiable();

Properties are a different story. In Moq, in addition to Mocks that carry expectations, you can generate stubs for properties that basically allow the properties to be set and have them return the values when the getter is called. You can do this for individual properties (and optionally provide an initial value) or you can do it for all properties with a single call using .SetupAllProperties().

Rhino.Mocks, on the other hand, doesn't provide the ability to track property values, so to get that same functionality, you'd need to use a callback (.Do() or .Callback()) and track the value yourself.

Moq can do mass verification in two ways. If you have created a mock that sets up expectations using .Expect() in Rhino.Mocks or .Verifiable() in Moq, you can use Moq's .Verify() method to validate just those expectations. Moq also provides a .VerifyAll() method which will validate all of the mocks and stubs you've created with .Setup().

Rhino.Mocks

Moq

Verify Mocks only

mock.VerifyAllExpectations();

mockWrapper.Verify();

Verify Mocks and Stubs

(not available)

mockWrapper.VerifyAll();

Controlling Mock Behaviors

Here are some of the general behavior modifications in Rhino.Mocks and their Moq equivalents:

Advanced Argument Constraints

Both frameworks provide ways to put advanced constraints on the arguments that trigger a mock. Below are examples -- you'll need to consult the framework documentation for the full list of available constraints.

Throwing an Exception Instead

This is pretty much a drop-in replacement when creating the mock/stub. Where Rhino.Mocks uses .Throw() for this purpose, Moq uses .Throws();

Testing Non-Public Members

With Rhino.Mocks, you can’t mock private or protected members, but you can mock internal members if you add an InternalsVisibleTo attribute for the Castle dynamic proxy assembly. Moq also uses the same proxy, so you'll still need to add the attribute, but Moq has the added benefit of being able to mock protected members. See the Moq Quickstart Guide for details on how to do this.