Meet the frameworks : Rhino v Moq v jMock : Part II

Story so far
We've seen how to
* setup expectations for calls on methods/properties.
* specify the number of times to be called.
* specify values to be returned

Now I move onto more involved scenarios.

#6:Throw an exception in response to an expected call on mockCollaborator.Method()
  • Rhino Mocks


[ExpectedException(ExceptionType=typeof(UnableToServeException),
MatchType=MessageMatch.Contains,
ExpectedMessage="Sorry for the inconvenience.")]
[Test]
public void Test_ExpectExceptionToBeThrown()
{
_mockChef.Expect(chef => chef.Bake(CakeFlavors.Pineapple, false)).Throw(new Exception());

_bakery.PlaceOrder(OrderForOnePineappleCakeNoIcing);
}

The Throw method tagged onto the end of the Expect does the trick of raising any derivation of Exception (here I've raised a generic Exception)
  • Moq


[ExpectedException(ExceptionType=typeof(UnableToServeException),
MatchType=MessageMatch.Contains,
ExpectedMessage="Sorry for the inconvenience.")]
[Test]
public void Test_ExpectExceptionToBeThrown()
{
_mockChef.Setup( chef => chef.Bake(CakeFlavors.Pineapple, false)).Throws<Exception>();
_bakery.PlaceOrder( OrderForOnePineappleCakeNoIcing );
}

Moq uses a generic Throws() to achieve the result
  • jMock


@Test
public void test_expectAndThrowException() throws OutOfIngredientsException
{
final Sequence aSequence = context.sequence("retryBake");
context.checking( new Expectations() {{
oneOf(_mockChef).bakeRealWorld( CakeFlavors.Pineapple, false );
will(throwException(new OutOfIngredientsException() ));
inSequence(aSequence);
oneOf(_mockInventory).replenishStocks();
inSequence(aSequence);
oneOf(_mockChef).bakeRealWorld( CakeFlavors.Pineapple, false );
inSequence(aSequence);
}});

_bakery.placeOrderRealWorld( OrderForOnePineappleCakeNoIcing() );
}

The will(throwException(exceptionInstance) after an expectation does the trick. Ignore the lines in Sequence (I'll get to them in Section#9)

Java's checked exceptions and explicit method specification (all the way up the call-chain) feels a bit too rigid to me (maybe due to my .Net exposure). So I've created an overload of Bake that throws an exception, to avoid adding a throws clause to every test method that has an expectation for Bake(). Worked for me.. although it's not the right thing to do. The joys of coding in a toy example!

void bakeRealWorld(CakeFlavors flavor, boolean withIcing) throws OutOfIngredientsException;


#7:Custom callbacks or blocks of code to execute when a mockCollaborator.Method() is called
Let me cook up a use for this. Let's say I want the first call to Chef.Bake throw an OutOfIngredientsException(), so that I can call ReplenishStocks() and retry. This time, the call to Chef.Bake should go through.

Just the kind of job for... custom Callbacks!

  • Rhino Mocks


[Test]
public void Test_ExpectWithCustomCallback()
{
int callbacks = 0;
_mockChef.Expect(chef => chef.Bake(CakeFlavors.Pineapple, false))
.Repeat.Times(2)
.WhenCalled(delegate(MethodInvocation mi) {
Console.WriteLine("Callback Params: {0}, {1}", mi.Arguments[0], mi.Arguments[1]);
callbacks += 1;
if (callbacks == 1)
throw new OutOfIngredientsException();

return;
});
_mockInventory.Expect(inv => inv.ReplenishStocks()).Return(true);

_bakery.PlaceOrder(OrderForOnePineappleCakeNoIcing);

_mockChef.VerifyAllExpectations();
_mockInventory.VerifyAllExpectations();
}

Tag on WhenCalled(delegateWithCustomCode) to the expectation. Also note that you have access to the method arguments as shown in the Console trace above.
  • Moq


[Test]
public void Test_ExpectWithCustomCallback()
{
var callbacks = 0;
_mockChef.Setup(chef => chef.Bake(CakeFlavors.Pineapple, false))
.Callback( delegate(CakeFlavors flavor, bool withIcing)
{ // any custom code
Console.WriteLine("Callback Params: {0}, {1}", flavor, withIcing);
callbacks += 1;
if (callbacks == 1)
throw new OutOfIngredientsException();

return;
}
);

_mockInventory.Setup(inv => inv.ReplenishStocks()).Returns(true);
_bakery.PlaceOrder( OrderForOnePineappleCakeNoIcing );

_mockChef.VerifyAll();
_mockInventory.VerifyAll();
}

Tag on an overload of Callback( customDelegate ) at the end of the Setup to specify custom code to be executed.
Moq gives you strongly typed callbacks with upto 4 parameters (Action is the biggest Action type in .Net; a restriction that will be lifted with .net 4.0). Argument access is a snap.

  • jMock


// http://www.jmock.org/custom-actions.html
@Test
public void test_expectAndInvokeCustomCallback()
{
context.checking( new Expectations() { {
oneOf(_mockChef).bake(CakeFlavors.Pineapple, false );
will( MyCustomCallback.tracingCallback() );
} } );

_bakery.placeOrder( new Order(CakeFlavors.Pineapple, false, 1) );
}
class MyCustomCallback implements Action
{
public void describeTo(org.hamcrest.Description description)
{
description.appendText("a custom callback to do what I deem fit! ");
}

public Object invoke(Invocation invocation) throws Throwable
{ // any custom code
System.out.println("Callback invoked with "
+ ((CakeFlavors)invocation.getParameter(0))
+ " and "
+ (((Boolean) invocation.getParameter(1)).booleanValue() ? "" : "no")
+ " icing!");
return null;
}
public static Action tracingCallback()
{
return new MyCustomCallback();
}
}

It may be due to my rusty Java but it turned out to be a whole lot of classes to achieve this with jMock

#8:Raise an event from a mock collaborator
This one is very handy when testing GUIs using a ModelViewPresenter (or related pattern)

Our inventory raises an event when we're running low on a particular ingredient. The bakery can use this notification to tell the Chef to go easy on that ingredient, while we stock our supplies.

  • Rhino Mocks


[Test]
public void Test_RaiseEventFromMock()
{
_mockChef.Expect(chef => chef.GoEasyOn("Sugar"));

_mockInventory.Raise(inv => inv.RunningLowOnIngredient += null,
this, new StockEventArgs("Sugar"));

_mockChef.VerifyAllExpectations();
}

To raise an event, invoke the Raise method on the mock with a null subscription to the event & the arguments to be passed onto the event handler method.
  • Moq


[Test]
public void Test_RaiseEventFromMock()
{
_mockChef.Setup(chef => chef.GoEasyOn("Sugar"));

_mockInventory.Raise(inventory => inventory.RunningLowOnIngredient += null, new StockEventArgs("Sugar"));
_mockChef.VerifyAll();
}

Identical to Rhino except for the fact that you don't have to specify the 'sender' parameter.
  • jMock

Java doesn't support events as first-class citizens. You need to manually implement the publisher-subscriber pattern.

#9:Argument Constraints
Sometimes, we do not want to / cannot specify the exact arguments with which a method on a collaborator will be called as part of the expectation. In such cases, we use constraints on the arguments, which must be met for the expectation to be met.
e.g. from the previous example, lets say we don't know the value of the Low-stock-ingredient at compile-time. We have a variable into which we can fetch the ingredient and which we can use to compare against the actual value.
In short we want to specify a Predicate (a function which returns true/false) for an argument as a constraint.

  • Rhino Mocks


[Test]
public void Test_ConstrainingArguments()
{
var itemAboutToGoOutOfStock = "Eggs";
_mockChef.Expect(chef => chef.GoEasyOn(
Arg<string>.Matches (ingredient => ComplexCheck(itemAboutToGoOutOfStock, ingredient))));

_mockInventory.Raise(inventory => inventory.RunningLowOnIngredient += null,
this, new StockEventArgs(itemAboutToGoOutOfStock));
_mockChef.VerifyAllExpectations();
}
private bool ComplexCheck(string expected, string actual)
{
return expected.Equals(actual); // any complex test
}

So here we use Arg.Matches(predicate) to do a complex constraint on the string argument for Chef#GoEasyOn(). There are a bunch of other helpful constraints - explore the Arg type docs (or the intellisense popup) for more.
  • Moq


[Test]
public void Test_ConstrainingArguments()
{
var itemAboutToGoOutOfStock = "Eggs";
_mockChef.Setup(chef => chef.GoEasyOn(
It.Is<string>(ingredient => ComplexCheck(itemAboutToGoOutOfStock, ingredient))));

_mockInventory.Raise(inventory => inventory.RunningLowOnIngredient += null,
new StockEventArgs(itemAboutToGoOutOfStock));
_mockChef.VerifyAll();
}
private bool ComplexCheck(string expected, string actual)
{
return expected.Equals(actual); // any complex test
}

Moq has It.Is(predicate) for this purpose. Explore the type documentation (or the intellisense popup) for more helper constraints.
  • jMock

The example is different. Here we are constraining the arguments to the Bake call with a predicate.

//http://www.jmock.org/custom-matchers.html
@Test
public void test_expectAndCheckArgs()
{
context.checking( new Expectations() { {
oneOf(_mockInventory).isEmpty();
will(returnValue(false));
oneOf(_mockChef).bake(
with( FlavorMatcher.aPineappleFlavoredCake() ),
with( any(boolean.class)));
}} );
_bakery.pleaseDonate( OrderForOnePineappleCakeNoIcing() );
}


class FlavorMatcher extends TypeSafeMatcher<CakeFlavors>
{
public boolean matchesSafely(CakeFlavors flavor)
{ // any complex test

return flavor == CakeFlavors.Pineapple;

}
public void describeTo(org.hamcrest.Description description) {
description.appendText("a cake with pineapple flavor ");
}

@Factory
public static Matcher<CakeFlavors> aPineappleFlavoredCake()
{
return new FlavorMatcher();
}
}

once again more classes than I'd liked (Disclaimer: rusty java programmer could be the problem).

Use with(matcherInstance) in place of arguments in the expectation. Derive a new Matcher derived class with your custom check.


#9:Expect a sequence of calls in a specific order
Ordered Expectations: Looking at the test in Section#4 - the test can be satisfied by the following implementation

public void PleaseDonate(Order order)
{
_chef.Bake(order.Flavor, order.WithIcing);
var isEmpty = _inventory.IsEmpty;
}

which is not what we were getting at. Seems like the test is missing something... the order of calls! Chef.Bake should be called after Inventory.IsEmpty.
  • Rhino Mocks


[Test]
public void Test_ExpectCallsInOrder()
{
var mockCreator = new MockRepository();
_mockChef = mockCreator.DynamicMock<Chef>();
_mockInventory = mockCreator.DynamicMock<Inventory>();
mockCreator.ReplayAll(); // to avoid setting up an expect for an event handler subscribe in the following ctor.

_bakery = new Bakery(_mockChef, _mockInventory);

using (mockCreator.Ordered())
{
_mockInventory.Expect(inv => inv.IsEmpty).Return(false);
_mockChef.Expect(chef => chef.Bake(CakeFlavors.Pineapple, false));
}

_bakery.PleaseDonate(OrderForOnePineappleCakeNoIcing);

_mockChef.VerifyAllExpectations();
_mockInventory.VerifyAllExpectations();
}


Woooaah! What just happened? Have a seat ; take a deep breath.
Ordered expectations have been a feature of Rhino Mocks; however the v3.5 syntax revamp hasn't made an impact here. This took some doing .. Turns out you need to go old-skool for a bit.
The key:
* Create a new MockRepository instance and invoke the DynamicMock method (instead of the static MockRepository.GenerateMock )
* Use the Ordered block to setup expectations in a specific order

  • Moq


[Test]
public void Test_ExpectCallsInOrder()
{
var sequence = String.Empty;
_mockInventory.Setup(inv => inv.IsEmpty).Returns(false)
.Callback(delegate { sequence += "1"; });
_mockChef.Setup(chef => chef.Bake(CakeFlavors.Pineapple, false))
.Callback(delegate { sequence += "2"; });

_bakery.PleaseDonate(OrderForOnePineappleCakeNoIcing);

Assert.AreEqual("12", sequence, "Calls not in expected order!");
_mockChef.VerifyAll();
_mockInventory.VerifyAll();
}

Last time I checked (Jan25,2010) Moq does not support this out of the box. However you could work around this with a collecting object. Very naive.. you could come up with better solutions to fit your exact context.
  • jMock


@Test
public void test_expectCallsInSpecificOrder()
{
final Sequence pleaseDonateSequence = context.sequence("pleaseDonate");
context.checking( new Expectations() {{
oneOf(_mockInventory).isEmpty();
inSequence(pleaseDonateSequence);
will(returnValue(false));
oneOf(_mockChef).bake(CakeFlavors.Pineapple, false);
inSequence(pleaseDonateSequence);
}});

_bakery.pleaseDonate( OrderForOnePineappleCakeNoIcing() );
}

jMock has the shortest syntax for ordered expectations. You create a named Sequence object and then tag the name along with each expectation (listed in the expected order).

So there you have it. If it was a showdown, jMock would be ahead of Moq and Rhino Mocks would be just a sliver behind Moq.

JMock:
+ has a nice readable concise API for number of invocations and ordered expectations

Moq:
+ has a nice mechanism for type-safe custom callbacks and argument constraints

Rhino:
+ isn't bad. Does everything. However even with the v3.5 syntax revamp, it is a little unintuitive as compared to the others. The documentation was a bit noob-unfriendly, when I needed it. However it is the only option if can't use .net 3.5 for your tests (which should be rare).

Meet the frameworks : Rhino Mocks v Moq v jMock : Part 1

If you've been near any TDD-infected person, you're sure to have heard about Mock frameworks (or served as a by-standing casualty in a classicist v Mockist skirmish). Then you have to look. At first you're apprehensive, it looks like too much work (defining interfaces, creating mocks, expectations, et. all). Soon you're cornered by a Data Access object or a Network stream and you have no choice. You dip your feet into the pool of mocks.. soon enough you're splashing around like a silly kid creating mocks willy-nilly (they're free). Unknown to you, the pool has some whirlpools that suck you in when you're having too much fun and not paying any attention. In the end, it's like mock-Children of the Corn..

I'm a sucker for horror stories (and there's that other little matter of being biased towards state-based tests.) As with most things, there is more than one way to use a tool - mock frameworks are no exception. The folks at mockobjects.com have a new book out which explains the right way (not read it yet; maybe I'll still be converted into a mockist.)

Personally my pet-peeve with mock frameworks has been the learning curve. Usually you don't have a dedicated time-slot to learn a mock framework (and that's kind of a good constraint since the mock frameworks are flexible, powerful and consequently huge); I'd bet that most of us learn them while trying to get a test to pass. Nothing like a reluctant mock framework with cryptic error messages between you and a green bar, to get you into real-curse-practice. The only thing that comes a distant second is "Which is better? Rhino Mocks or Moq ?" from people who haven't explored either of them. If both of them scratch your itch, take a pick!

So I've tried to list down the most probable scenarios and try each of them with RhinoMocks, Moq and jMock (always wanted to write some tests in jUnit).

  1. Expect a Call on mockCollaborator.method()
  2. Expect a call on mockCollaborator.getProperty and return something
  3. Expect n calls to mockCollaborator.Method()
  4. Return values from mockCollaborator.Method()
  5. Expect no call (Don't call me!)
  6. Throw an exception in response to an expected call on mockCollaborator.Method()
  7. Custom callbacks or blocks of code to execute when a mockCollaborator.Method() is called
  8. Raise an event from a mock collaborator
  9. Argument Constraints
  10. Expect a sequence of calls in a specific order
You could use this to make your own choice (which is only yours to make). I've written this down as a self-reference for the next time I'm wondering "Why doesn't this @#&*(@ test fail?' or 'How is this test passing?'

A template for interaction-tests



For state-based tests, I'd usually write my assert first, step back to the action that will lead to the assert and finally arranging everything for the test to work. However this doesn't exactly work for interaction-based tests: In this realm, it's more helpful to write the action first, then the expectations and other steps for arrange and finally assert (which sometimes is just verifying that the expected mocks were called. Some frameworks like jMock do it automatically at the end of the test.)
Arrange
  1. create mock objects for collaborators that you want to mock( not Stub. I hope you've read Martin Fowler's paper [link] on the difference.)
  2. Create your test subject (here a Bakery type) and inject the mock collaborators via ctor/setter methods.
  3. Define the interaction via 'expects'. e.g. I expect the test subject to call methodX on collaboratorA with these parameters.
Act
  1. State the action/behavior that is the primary focus of this test
Assert
  1. Assert any state-change (if applicable)
  2. Verify all expected calls on the collaborators were called.


Source Code:
The source code for this series is available for browse/checkout (you'll need subversion to checkout) at
Dot Net code
Java code

#1: Expect a Call on mockCollaborator.method()
  • Rhino v3.5 (with NUnit 2.4.8)


Let's see how we do this in Rhino Mocks 3.5 - use the above section to work through this example.
Rhino mocks has changed with a (IMHO noob-friendly/simpler) syntax with version 3.5 - Prior to that an explicit record-replay style was the norm. So if you're using a prior version, try moving to v3.5. (There is a forsaken commented-out source file in the above mentioned link for old-skool Rhino).

To declare that you expect a method to be called, you use the Expect method on the respective mock object. Lambda expressions, Generics and type-inference result in compile-time checks and Intellisense guiding you all the way.
The below expectation reads "On the mockChef, expect Bake to be called with Vanilla and false as arguments." (when someone calls PlaceOrder() on the bakery, which employs the Chef)
I'm not going to post the code to make this pass inline (for honoring the memory of brevity in blog posts). I suggest you try TDDing your way through like me / refer to the source repository.



[Test]
public void Test_ExpectMethodCall()
{ // arrange : create mocks
var mockChef = MockRepository.GenerateMock<Chef>();

// arrange: inject dependencies
Bakery bakery = new Bakery(mockChef);
// arrange: expect the Bake method on Chef to be called
mockChef.Expect(chef => chef.Bake(CakeFlavors.Vanilla, false));

//act
bakery.PlaceOrder(new Order { Flavor = CakeFlavors.Vanilla, WithIcing = false, Quantity = 1 });

//assert
mockChef.VerifyAllExpectations();
}
  • Moq v 2.0.5 (with NUnit 2.4.8)
Moq was the new kid on the block challenging the leading .Net mock frameworks with .Net3.5 lambda-expressions powered snappy syntax.



[Test]
public void Test_ExpectMethodCall()
{
//arrange
var mockChef = new Mock<Chef>();

//arrange: inject dep
var bakery = new Bakery(mockChef.Object);
// arrange: expect
_mockChef.Setup(chef => chef.Bake(CakeFlavors.Vanilla, true));

//act
_bakery.PlaceOrder(new Order { Flavor = CakeFlavors.Vanilla, WithIcing = true, Quantity = 1 });
//assert
_mockChef.VerifyAll();
}

Differences
#1: mockChef.Object is the mock collaborator; this is a common stumble for people new to Moq. I think (unverified) this is due to Moq's design of not having a different Repository or Mockery type.
#2: Moq uses Setup for expecations (instead of Rhino's Expect)

  • jMock 2.5.1 (with jUnit 4.8.1)

jMock is the Java mock framework distilled from the experience of the gurus at mockobjects.com ; they have a new book out and are the recognized pioneers of the "Mock objects" technique. I highly recommend their second revision of the acclaimed 'Mock Roles not objects' paper.
So let's see how the test looks like in jMock:


Mockery context = new JUnit4Mockery();

@Test
public void test_expectCall()
{
Chef mockChef = context.mock(Chef.class);
Bakery bakery = new Bakery(mockChef);

context.checking( new Expectations() { {
oneOf(mockChef).bake(CakeFlavors.Pineapple, false );
} } );

bakery.placeOrder( new Order(CakeFlavors.Pineapple, false, 1) );
// mockChef.Verify() - autoverified : framework :)
}


Differences
#1: jMock has a more fluent approach to specifying expectations - look inside the Expectations creation. It reads 'Expect one invocation on mockChef of method bake with parameters Pineapple and false. Refer to the nicely written jMock cheatsheet in case you're feeling a bit lost.
#2: You don't need to explicitly verify expectations - automatically done at the end of a test case.


#2 Expect a call on mockCollaborator.getProperty and return something
I've factored out common code into a SetUp method to shorten the code snippets. In general, .Net properties = one get_property method + one set_property method + one backing field. Syntactic sugar!

So when someone queries Bakery.IsOpen, check to see if the Chef is available.

  • Rhino Mocks


[Test]
public void Test_ExpectPropertyGet()
{
_mockChef.Expect(chef => chef.IsAvailable).Return(true);
Assert.IsTrue(_bakery.IsOpen);

_mockChef.Expect(chef => chef.IsAvailable).Return(false);
Assert.IsFalse(_bakery.IsOpen);

_mockChef.VerifyAllExpectations();
}


Note the new Return method tagging along with the Expect to signify what should be returned when the Bakery makes a call to Chef#IsAvailable
  • Moq


[Test]
public void Test_ExpectPropertyGet()
{
_mockChef.Setup(chef => chef.IsAvailable).Returns(true);
Assert.IsTrue(_bakery.IsOpen);

_mockChef.Setup(chef => chef.IsAvailable).Returns(false);
Assert.IsFalse(_bakery.IsOpen);

_mockChef.VerifyAll();
}

Moq calls it Returns which IMHO reads better.
  • jMock

Java does not have properties as first class language features. They are manually implemented as accessor/mutator method pair and a backing field.

#3: Expect n calls to mockCollaborator.Method()
So if I place an Order for 3 Pineapple cakes, I'd expect the Chef#Bake to be called thrice.
  • Rhino Mocks


[Test]
public void Test_ExpectMultipleCalls()
{
_mockChef.Expect(chef => chef.Bake(CakeFlavors.Pineapple, true)).Repeat.Times(3);

_bakery.PlaceOrder(new Order { Flavor = CakeFlavors.Pineapple, WithIcing = true, Quantity = 3 });

_mockChef.VerifyAllExpectations();
}

Tag on the Repeat property to the Expect if you expect it to be called n times.
Caveat: the test fails if the mock isn't called at least 3 times. If you call it 3 or more times, the test passes. So if you have a need for exactly thrice, dive into the rhino mocks docs and let me know if you figure out a way to make it work.
  • Moq


[Test]
public void Test_ExpectMultipleMethodCalls()
{
_bakery.PlaceOrder(new Order { Flavor = CakeFlavors.Pineapple, WithIcing = false, Quantity = 3 });
_mockChef.Verify( chef => chef.Bake(CakeFlavors.Pineapple, false), Times.Exactly(3), "Chef should have been called thrice!");
}


Differences:
#1. With Moq, you specify this during verification with an overload of Verify (as opposed to while defining expectations)
#2 This test will pass only if Bake is called Exactly thrice (unlike Rhino)

  • jMock


@Test
public void test_expectMultipleCalls()
{
context.checking( new Expectations() {{
exactly(3).of(_mockChef).bake(CakeFlavors.Pineapple, false);
}} );

_bakery.placeOrder( new Order(CakeFlavors.Pineapple, false, 3) );
}

jMock wins this one for readabililty.
#4: Return values from mockCollaborator.Method()

Refer to #2 for Rhino and Moq. You tag on a Return/Returns method call to the expectation.
Let's say the bakery being a charitable organization, responds to a PleaseDonate message at the end of the day from cake-loving orphans. The bakery will ask the Chef to bake one for them after checking to see if they have surplus stocks in inventory.

  • jMock


@Test
public void test_expectCallAndReturnValue()
{
context.checking( new Expectations() {{
oneOf(_mockInventory).isEmpty();
will(returnValue(false));
oneOf(_mockChef).bake(CakeFlavors.Pineapple, false);
}} );

_bakery.pleaseDonate( OrderForOnePineappleCakeNoIcing() );
}

jMock has a will method to signify what will happen when the method is invoked. Use the indentation (convention) so that it reads better.

#5:Expect no call (Don't call me!)
When the orphans send a PleaseDonate() and there are no surplus stocks in inventory, you wouldn't want to bother the overworked chef at the end of a weary day.
  • Rhino Mocks


[Test]
public void Test_ExpectNoCall()
{
_mockInventory.Expect(inv => inv.IsEmpty).Return(true);
_mockChef.Expect(chef => chef.Bake(Arg<CakeFlavors>.Is.Anything, Arg<bool>.Is.Anything))
.Repeat.Never();

_bakery.PleaseDonate(OrderForOnePineappleCakeNoIcing);

_mockInventory.VerifyAllExpectations();
_mockChef.VerifyAllExpectations();
}

Note: This snippet gives you a sneak peek of Argument Constraints. In short the second line states 'mockChef#Bake should not be called (irrespective of arguments)' Bring the .Repeat.Never() clause into plain view by placing it on a new line with one level of indentation.
  • Moq


[Test]
public void Test_ExpectNoCall()
{
_mockInventory.Setup(inventory => inventory.IsEmpty).Returns(true);
_bakery.PleaseDonate(OrderForOnePineappleCakeNoIcing);

_mockChef.Verify(chef => chef.Bake(It.IsAny<CakeFlavors>(), It.IsAny<bool>()), Times.Never());
_mockInventory.VerifyAll();
}

Differences:
#1 Moq takes a different path of leaving the invocation-count check till the very end. Use the Verify Overload with Times.Never() as in Section#3
#2 Argument constaints in Moq read slightly better than Rhino.

  • jMock


@Test
public void test_expectNoCall()
{
context.checking( new Expectations() {{
oneOf(_mockInventory).isEmpty();
will(returnValue(true));
never(_mockChef).bake( CakeFlavors.Pineapple, false );

}});

_bakery.pleaseDonate( OrderForOnePineappleCakeNoIcing() );
}

jMock doesn't hide intent with never() leading the expectation. jMock's API shows the thought that's been put into it.

5 down. 5 for the next part.