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.

My TDD Workshop

I was recently asked to conduct a workshop (read everyone-off-their-armchairs-and-type-with-me) on Test Driven Development. Now since this is something that I love (could not be any more apt for my 100th blog-post), I kind of "invested all of my self esteem in this presentation" as Dilbert would have said.

I don't have the code examples complete - I didn't like the way the GUI example turned out ; gonna give it another whirl soon.


Creative Commons License
Test driven development Workshop 2009 by Gishu Pillai is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.
Based on a work at docs.google.com.
Permissions beyond the scope of this license may be available at
my-tdd-workshop.html


My guiding principles were
  • to give the attendees a true taste of TDD (vs automated-tests after vs test-first programming)
  • to set up beacons to avoid the usual pits, which sink time, effort, people, projects
  • to condense what I felt were in the "must-know" category
  1. Test "driven" design - emergent design
  2. SOLID Principles
  3. Mocks and Dependency Injection
  4. Model View Presenter / Humble dialog way of building GUIs
  • to learn myself from the interaction (I've learned from a lot of people online. It 's only fair that I give back)
So I got onto google docs, fired up a presentation, wrote up a rough list of things that I considered important and off I went towards an initial draft. I asked around for a good non-toy problem for the code-alongs... to my surprise I didn't net that many.. so I settled for the Bowling Example of TDD yore (Ron Jeffries, Uncle Bob, et. all)
"Score a complete bowling game as per the standard scoring rules."

I also needed an extension to the problem that involved a bit of Mocks and GUIs (for some real world flavor) - so I extended the problem (of course with my "customer hat" on)
"Create a View/Display for the Bowling Game that shows pins rolled and score updates in real time."

I then tried to solve the problem myself. The second problem turned out to be more time-consuming than I imagined. (A definite possibility is that I had lost my touch with TDD and was rusty due to lack of practice - a shoutout to Naresh Jain, for helping me realize that)
Finally I published the draft online to the testdrivendevelopment yahoo group for scrutiny ; As always I got a lot of help and nice suggestions. (A big thank you! to all of you) I incorporated most of them - including expanding my 1-day plan to a 2-day (and finally a 3-day plan - Charlie Poole can go 'told you so')

I then conducted the first instance of the workshop with 13 attendees.
The first day went as per plan. TDD Origins, SOLID Principles, Bowling Game Part I.
However the second day, the rails came off. They loved the Rhino Mocks jumpstart - however coding along ate up a lot of hours. I skimmed the Moq equivalent exercise and somehow rushed through to the end. The grand-finale of building a GUI (which was supposed to illustrate how you can design incrementally and it's okay if you dont have a 30 page design-document blessed by the powers that be, if you pay attention to design all the time) had to be left as an "exercise for the attendee". I'll need to extend the workshop to a full 3 days next time.


Had the opportunity to do a lot of little experiments - like using a Chess Timer to time how much time I spent writing tests to code. Good fun overall! It also showed me that I need to tune my content a bit more - the anonymous feedback was encouraging. Scored a 100% on "Would you recommend this (session) to someone else" ? Just the impetus I needed to sink another bunch of hours tinkering with the content.

Testing .Net code with Cucumber and IronRuby

As promised, this is the culmination of this trilogy. The previous two posts were a jump-start on Cucumber to test Ruby code. Next I moved towards using Cucumber's plain text stories to test .Net code.Aslak Hellesoy has a wiki-post on how to do this ; however I found that you get eaten and spat out by a lot of IronRuby dragons along the way. So hold on..

1. Install the new DLR

First up install .Net Framework 4.0 (I have Beta1) - this has the new Dynamic Language Runtime (DLR) that makes things like IronRuby and IronPython possible.

2. Get the latest IronRuby release

Next we need to get IronRuby as a zip. Extract it to say d:\ironruby-0.9.0 Add the path to the bin folder to your PATH environment variable to avoiding lengthy paths. Drop to a command shell, type 'ir' to invoke the interactive IronRuby console. Type something simple to test if it works. It should.
>>>puts "Hello IronRuby"


3. Dragons ahead. Use diversion

But I hit a snag with this version of IronRuby, which had A BUG.

  • So I had to get the latest (8 Sep 2009 master to be precise) version of the source from the github repository to overcome that. You can download it as a zip or use git as you prefer. I got the zip
    ironruby-ironruby-90cdda82fd60f4b7e6d7d940501c586d55954466.zip (Could have used a shorter name)

  • Extract it to say d:\ir-src
    I hit a few path-too-long errors during extraction. Just keep skipping them. I think it's because of the rather large alphanumeric string which is the name of the top-level folder.

  • Once extracted, navigate to D:\ir-src\ironruby-ironruby-90cdda82fd60f4b7e6d7d940501c586d55954466\Merlin\Main\Languages\Ruby
    and open Ruby.sln in VS2008 (I have Dev Edition of VSTS.. Although it should build in VS Express Editions as per the docs - I couldn't get the solution to open in it.)
    Build Solution. At the end of it you should find the built binaries in
    D:\ir-src\ironruby-ironruby-90cdda82fd60f4b7e6d7d940501c586d55954466\Merlin\Main\bin\Debug

  • Rename that directory with the huge name to something like "ir".

  • Copy all built binaries and overwrite the ones from the 0.9.0 release's bin folder i.e. D:\ironruby-0.9.0\bin.


  • Open ir.exe.config in the same folder and update the Library paths element to the proper paths to folders within your ir-src folder. 'Handle with extreme care' or you'll lose hours chasing error messages. It should read
    Path#1 - D:\ir-src\ir\Merlin\Main\Languages\ (NOT D:\ir-src\ir\Merlin\External.LCA_RESTRICTED\Languages)
    Path#2 & #3 - D:\ir-src\ir\Merlin\External.LCA_RESTRICTED

    My xml looks like
    <set language="Ruby" option="LibraryPaths" 
    value="D:\ir-src\ir\Merlin\Main\Languages\Ruby\libs\;D:\ir-src\ir\Merlin\External.LCA_RESTRICTED
    \Languages\Ruby\redist-libs\ruby\site_ruby\1.8\;D:\ir-src\ir\Merlin\External.LCA_RESTRICTED\Lang
    uages\Ruby\redist-libs\ruby\1.8\" />




4. Wrapper script ICucumber

Lastly we need a wrapper script to invoke cucumber with Ironruby. Create a file called icucumber.bat under your Ruby bin folder i.e. D:\Ruby\bin\icucumber.bat with the following text.

REM Update with appropriate values for GEM_PATH, Ruby bin and the path to ir.exe
@ECHO OFF
REM This is to tell IronRuby where to find gems.
SET GEM_PATH=d:\ruby\lib\ruby\gems\1.8
"D:\ironruby-0.9.0\bin\ir.exe" -D -X:ExceptionDetail "d:\ruby\bin\cucumber" %*


5. Back to our example from the previous two posts.
The .feature file stays unchanged.
Delete c:\cukes\dot_net_features\support\BowlingGame.rb ; since we're going to implement the same in C# this time around as
c:\cukes\dot_net_features\support\BowlingGame.cs




namespace CukesDemo
{
public class BowlingGame
{
public void roll(int pins_knocked_down)
{
Score += pins_knocked_down;
}

public int Score
{
get; set;
}
public bool Over
{
get { return false; }
}
}
}


Also create a small batch file to compile it to a DLL (Assumes csharp compiler is on the PATH).
c:\cukes\dot_net_features\support\Compile.bat

IF EXIST bin GOTO COMPILE
MKDIR bin
:COMPILE
csc /t:library /out:bin/BowlingGame.dll bowling_game.cs


Finally back to our step definitions to check the glue. Four changes needed - explained in comments.
cukes\dot_net_features\step_definitions\bowling_game_steps.rb


# CHANGE 1 : Add bin folder to load-path
$:.unshift(File.dirname(__FILE__) + '/../support/bin')
# CHANGE 2 : Get BowlingGame.dll
require 'BowlingGame'

Given /^I am starting a new game$/ do
# CHANGE 3 : Use Namespace::ClassName.new
@game = CukesDemo::BowlingGame.new
end

When /^I roll (\d+) gutter balls$/ do |count|
count.to_i.times{
@game.roll(0)
}
end

Then /^the score should be (\d+)$/ do |expected_score|
@game.score.should == expected_score.to_i
end

Then /^the game should be over$/ do
# CHANGE 4 : be_over passes even if Over returns false. Don't know what is the equiv of over?

in .Net
#~ @game.should be_over == true
@game.over.should == true
end

When /^my rolls are (.*)$/ do |rolls|
rolls.split(' ').each{|roll|
@game.roll(roll.to_i)
}
end


Now for the grand finale, run Cucumber to verify our .Net DLL via IronRuby !!!
[Cukes_06.jpg]

HTH

Scenario Outlines and Tagging in Cucumber

Post#2 in this trilogy.

Scenario Outline

Scenario tables are similar to Fit's ColumnFixture and NUnit's RowTest. You run the same scenario with different inputs each time.
Let's go back to our plain text feature and add the following.


Scenario Outline: score should be as per the std rules
Given I am starting a new game
When my rolls are <rolls>
Then the score should be <score>

Scenarios: lets go bowling
| rolls | score |
|5 2 | 7 |
|5 5 5 | 15 |


The key things to remember here are the 'Scenario Outline:' marker to indicate that it is an outline. We then have placeholders within angular brackets. The Outline is then followed by one or more tables identified by the marker 'Scenarios:'
The next line should contain column headers which correspond with the placeholders in the outline. Cucumber would substitute the values to run each row against the Outline.

SARC and it should fail. Let's go fix that up in bowling_game.rb


class BowlingGame
attr_reader :score
def initialize
@score = 0
end
def roll( pins_knocked_down)
@score += pins_knocked_down
end
def score
@score
end
def over?
true
end
end


SARC. Now you should see this nice listing.
[cukes_05.jpg]

Tagging

You can tag a scenario (or a feature) with one (or more) tags.
@important, @fast
Feature: Bowling Game Score Calculation
In order to let the player know his score


By default, cucumber runs all .feature files in the features subfolder. You can group features in different subfolders as well e.g. I can define a new.feature within a new_features subfolder, which can then be run with
>cucumber new_features

Overtime, it can get crowded with lots of subfolders. But tagging is here to save the day..
To run only features/scenarios marked 'fast'
>cucumber --tags @fast

To run features/scenarios that are not marked 'fast'
>cucumber --tags ~@fast


So that's another way to quickly sort out your tests.

Language Support

The next thing you'd probably want to know (just in case you need it) is that cucumber speaks multiple languages. You can write your .feature file in any language - provided that the necessary entries are made in the resource file - languages.yml.

Next post - getting cucumber to test a .Net app with some help from IronRuby. Piqued?


Resources on BDD / Cucumber (although I felt the majority were too entwined with Rails (e.g. WebRat for testing Web Apps via free step definitions) but then that very well could be the major user-base for cucumber right now.)

Green in 30 mins : Getting Started with Cucumber (a test framework for BDD)

Prologue:
BDD is TDD with an outside-in (top-down) bent.
The way to tackle any new feature request is to ask Why 5 times? An you should arrive at one of Protect Revenue, Increase Revenue or Manage Cost. If not, chances are you’re building something that is not needed.
A feature can be summarized in a few lines as (ala Mike Cohn’s user story format)


As a <role>
I want <feature>
So that <value>



Dan North began this journey with JBehave.
It evolved over time into a Ruby gem - RSpec courtesy David Chelimsky n co. RSpec consisted of two parts - example runner and a story runner. The story runner runs features (think big cog) written up as plain text files which can be ‘executed’ (via some developer-added connecting-glue code in a separate location). The example runner (think small cog) is a bunch of module specs that make the feature happen. (think xUnit for BDD).
The RSpec story runner has now been simplified/improved and become Cucumber – a really neat little tool by Aslak Hellesoy. There are others too who have contributed to this movement like Dave Astels, et. all


You can still use RSpec example runner in tango with Cucumber or you could stick with xUnit under the hood instead of RSpec.
Enough prologue for today.

Now I've spent 3-4 days chasing hyperlinks and watching screencasts (links at the end of Post#2 in this series), this post should give you a rolling start on cucumber.


Step1# Installation

You need a few Ruby Gems to get rolling. (RSpec & Win32Console not mandatory)

gem install rspec
gem install cucumber
gem install win32console


I have rspec (1.2.8) | cucumber (0.3.99) | win32console (1.2.0). Try ‘cucumber –help’ to verify this step. Win32console is for color output on Windows.

Step2# Lets go bowling

I’ll take the popular ‘Score a bowling game’ TDD Kata as an example.
So we begin with a feature. (I’ll skip the pop-the-why-stack ; this feature falls into the ‘protect revenue’ category). Find a nice empty directory let’s say c:\cukes. Create a features subdirectory within it.
We create a new file : features\bowling_score.feature and type this in. This is called the feature narrative – it’s just a descriptive block of text. However the form is slightly different the context/value clause rises to the top with the prefix In order to <business value>. Spotlight on business value!
Note: Indentation matters! Spaces preferred.

Feature: Bowling Game Score Calculation
In order to let the player know his score
As a CEO of TheBowlingInc
I want to calculate the score at the end of a bowling fame


Next we Save And Run Cucumber from the c:\cukes directory. This step I hereby alias to SARC. This outputs

c:\cukes>cucumber
Feature: Bowling Game Score Calculation
In order to let the player know his score
As a CEO of TheBowlingInc
I want to calculate the score at the end of a bowling fame

0 scenarios
0 steps
0m0.000s


So now that prompts us : we need Scenarios. A Feature may contain multiple scenarios (which collectively validate the feature).
A Scenario is executable. A Scenario takes the form

Scenario: <text description>
Given <context>
When <action>
Then <user-visible outcome>


So we expand our feature like this.

Feature: Bowling Game Score Calculation
In order to let the player know his score
As a CEO of TheBowlingInc
I want to calculate the score at the end of a bowling fame

Scenario: All Gutters score 0
Given I am starting a new game
When I roll 20 gutter balls
Then the score should be 0
And the game should be over


In addition you can write And <step> to have multiple steps – the above example is equivalent to 2 Then clauses. You can use it under Given/When too. Save and run cucumber again. (or SARC from here on)

[cukes_01.jpg]

For some reason the snippets don’t show up. So we play a little trick. Create a subfolder under features called step_definitions. Create a new blank file called bowling_game_steps.rb in it. Run cucumber again. Now you should see some snippets. Copy them from the console and paste into the blank file. SARC. You should now see that the first step is shown as a TODO and the rest are skipped (and in a different step-color to boot)

The first snippet looks like


Given /^I am starting a new game$/ do
pending
end


We need to define a “step” – specify the action to be taken i.e. when cucumber encounters a matching Given clause for the regex, what action should it take? You define that as the content of the block. Let’s say we want to create a new instance of a game. So replace `pending` with
`@game = BowlingGame.new`
SARC and now we have a familiar color – Red (of the Red-Green-Refactor fame). We’re notified that our step has failed.


[cukes_02.jpg]

We have no class called Bowling Game yet. Create a new subfolder under features called support to house our app classes. Create a new file in there ; features\support\bowling_game.cs

class BowlingGame; end

SARC and we’re green…. partially.. better than red. Cucumber now points us to the next step.

[cukes_03.jpg]

I’ll define all the steps like this.. while you take a breather. There. The updated version

Given /^I am starting a new game$/ do
@game = BowlingGame.new
end

When /^I roll (\d+) gutter balls$/ do |count|
count.to_i.times{
@game.roll(0)
}
end

Then /^the score should be (\d+)$/ do |expected_score|
@game.score.should == expected_score.to_i
end

Then /^the game should be over$/ do
@game.should be_over
end

When /^my rolls are (.*)$/ do |rolls|
rolls.split(' ').each{|roll|
@game.roll(roll.to_i)
}
end



NOTE:
  1. The second step is an example of a parameterized step. If the regex in the step definition contains groups, the matched contents are passed in as parameters to the block for the step. Parameter passed in are strings so you need to convert it to the right type before use. Standard regexp rules apply for matching groups. So now the step can match both ‘When I roll 5 gutter balls’ and When I roll 20 gutter balls’. You also see parameters highlighted distinctly in cucumber output. Cool!
  2. Then steps use a new should method which is added to all objects. You can read more about such helper methods here and here
  3. Cucumber tells after each step what needs to be done next. This rhythm is similar to the TDD approach.


Here’s the updated bowling_game.rb with ‘the simplest thing that could possibly work’

class BowlingGame
def roll( pins_knocked_down)
end
def score
0
end
def over?
true
end
end


SARC this time we specify the no source
option as a CL argument

 >cucumber –s 


[cukes_04.jpg]
And we’ve reached the promised land - plain text file story/features that can be verified automatically at the push of a button. That's pretty cool.

Just to reiterate the folder structure.


[folder_hier.jpg]

In the next post, we move up the learning curve with Scenario tables and tagging.

How to talk to a C# / ASP.Net web service via Ruby / Rails

Maybe not the right answer.. but I took the path of least resistance and succeeded. Yay Ruby!

First I did a dummy Asp.net Xml Web service as shown in this MSDN walkthrough which does F to C temp conversion. This meant that I can access my legacy/existing C# code without any interop hassles. Yes it is SOAP based (and old-school) but it will have to do for now. You can test out the web service via a dummy stub page that exercises the web service. You can also infer the needed urls from this page.

Next I found this uber-blog post by Ryan Heath and it was all downhill after that.

You write a wrapper Ruby class like this which gets the WSDL and sets itself up. You can then just call your Web methods on it!


   require 'soap/wsdlDriver'

class TempConverterWrapper
attr_accessor :endpoint, :service_name
def initialize(endpoint, service)
@endpoint = endpoint
@service = service
end

def convert_fahrenheit_to_celsius(temp)
soap = wsdl.create_rpc_driver
response = soap.convert_fahrenheit_to_celsius(:temp_in_fahrenheit => temp)
soap.reset_stream
response.convert_fahrenheit_to_celsiusResult
end


private
def wsdl
puts "http://#{@endpoint}/#{@service}.asmx?WSDL"
SOAP::WSDLDriverFactory.new("http://#{@endpoint}/#{@service}.asmx?WSDL")
end
end



Your main / irb code to exercise this web service. More bang / LOC!

puts "Enter a fahrenheit value to convert to celsius... via a Web Service"
temp_fahrenheit = gets.to_f

wrapper = TempConverterWrapper.new('localhost:1464', 'TemperatureConverter')
puts "The corresponding celsius value is #{wrapper.convert_fahrenheit_to_celsius(temp_fahrenheit)}"

How to show a Tree (TreeView) in a Rails view?

Well there seems to be no one-way for displaying a tree in Rails. But it has to be some javascript/AJAX doing its thing with CSS on HTML lists. So I took a look at YUI Tree (the first thing that google threw up) but it felt bloated and the learning curve was a bit too steep. Some time later.. I found a tree plugin for JQuery and also found that there is a RailsCast to use JQuery with Rails (so I knew its possible to interop).
I've been wanting to look at what JQuery is - with the massive good-will it is building up. Did a couple of tutorials 1 and 2 on their site to get started. Downloaded the jquery.js file (1 file for all the goodness !! awesome).
Next it's time to download the zip for the excellent JQuery tree plugin by Jorn Zaefferer - incidentally its the same person who wrote the second tutorial. I felt better about my chances for success.

I'm assuming you have a Rails app and the code for your hieararchy all done to this point. It's going to be a simple tree showing the hierarchy (no fancy AJAX callbacks or delayed loading of children... although I think its supported)

Unzip the treeview plugin folder v1.4 (it has a version of jquery bundled too inside the lib subfolder). I see
  • jquery.treeview.XXX.js (the javascript files) : Moved them to my public\javascripts folder within my Rails project folder. Also copied the lib subfolder here.
  • jquery.treeview.css (the CSS stylesheet) : Moved them to my public\stylesheets folder
  • images subfolder : Moved the images in this folder to a new subfolder public\images\jquery.treeview.images
Now the CSS file has references to the images. So do a find-replace to make sure all the images are reachable in their new locations; "url(images/" becomes "url(../images/jquery.treeview.images/"

I have a show action on my controller that creates @root_node which is a typical Node object with a Children attribute - an array of child nodes. So now we need something to render it as an hierarchical HTML list - a Rails helper method for your controller



  def display_segment( node )

html = "<li>"
node_class = node.children.length == 0 ? "file" : "folder"
html << "<span class=\"#{node_class}\">#{h(node.to_s)} </span>"
html << "<ul id=\"children_of_#{h(node.sid)}\">"
node.children.each{|child_node|

html << display_segment( child_node )
}
html << "</ul></li>"
end



Let's also take a look at the view show.html.erb



<html>
<head>
<h3> You are viewing <%= @data_file_path %> </h3>

<title><%= controller.action_name %></title>
<%= stylesheet_link_tag 'appstylesheet'%>
</head>

<body>
<ul id="my_tree" class="filetree">
<%= display_segment(@root_node) %>
</ul>

</body>
</html>


Things to note
  • First we need an enclosing ul block with css class set to filetree. This would be picked up our custom javascript snippet to JQuery-magically turn into a tree. So we need to make a note to give it a good id - here my_tree
  • Next the content is rendered via our recursive helper function. Children of a node are in a nested ul block. Each leaf-node is a li item and has css class as "file". parents have css class as "folder"
So now it should look something like this.



Now the stage is set for JQuery to do its thing. First lets introduce these 2 lines to the head tag of our view.


<%= javascript_include_tag 'lib/jquery', 'jquery.treeview', 'custom' %>
<%= stylesheet_link_tag 'jquery.treeview.css' %>


So we say we want to use the jquery javascript file, followed by the treeview plugin and finally our own custom javascript file that we'll write next.
We also want to use the treeview CSS stylesheet. You can do a "View Source" in firefox to see what the translated HTML looks like - std. stuff.

We're nearing the end here - Our \public\javascripts\custom.js file to sprinkle some JQuery dust on this thing


$(document).ready( function() {
$("#my_tree").treeview();
} );


Here we're giving a function to be executed when the page/document is ready. This function finds our top-level list element with id = "my_tree" and calls the treeview() method on it.



Victory Jig time!

Illustrated How to do a simple C++ DLL project in Visual Studio ?

Agreed that it isn't a big deal ... however I struggle with this everytime I dip my toes after a long managed stint.. and after a question on stackoverflow - it seems I'm not alone.

So here goes.. Fire up Visual Studio

Ctrl+Shift+N to go to the new project dialog or Right click on the Solution Node - Add - New Project... Press Next instead of Finish to go to the next screen.






So when I do that I have the following structure.
  • Stdafx.h & stdafx.cpp – defines and includes standard header files. Leave unmodified.
  • WinHookFacade_VS2005.cpp – defines the DLL Main function (entry point). Leave unmodified unless you have your very own dllmain.cpp with custom code.
  • Readme.txt – just a text file, you can stuff some info in.


Try to build the project. It should build fine.. do it just to be sure.
Next step include all your .h and .cpp into the project. Right click on the project in solution explorer - Add - Existing item..

You may have build failures.. now its time to enter the maze of C++ Project settings

C++ Settings




If you want additional directories to be looked for resolving header includes. Right click on Project Node - Properties
IMPORTANT: Check the Configuration combobox to read “All Configurations” each time you change a project setting else you risk the debug and release configurations getting out of sync.




Also for some reason, precompiled headers are frowned upon at my workplace. So I turn them off too..



Define any preprocessor symbols you want to.
DETOUR example.. WINHOOKFACADE_EXPORTS is a symbol defined here - which will cause my functions to be exported from here. Referencing projects will not have this symbol defined and will import my functions. The header files begin like this



#ifdef WINHOOKFACADE_EXPORTS
#define WINHOOKFACADE_API __declspec(dllexport)
#else
#define WINHOOKFACADE_API __declspec(dllimport)
#endif

void WINHOOKFACADE_API Hook();


Also in this case, you may want different symbols defined in both configurations. E.g. DEBUG is defined only in Debug configuration and so on.. so change the Configuration Combobox accordingly before making changes.



Linker Settings



To change the default location of the built binary file: E.g. I want the output to be generated in a SolutionDir\bin\Debug or Release. So you can use the helpful macros by pressing the tiny button on the right of the input field
$(SolutionDir)bin\$(ConfigurationName)\$(ProjectName).dll


I also keep the lib files that I need to link to in SolutionDir\bin\lib subfolder. So specify the additional folders to scan for .lib files



To specify the lib files you need to link to...



To specify where the lib file for the current project should be generated. In my case I want it to also go in under SolutionDir\bin\lib and named WinHookFacade_Debug.lib or WinHookFacade_Release.lib
Use the GUI macro helper thingie to come up with your own incantation. In my case it is

$(SolutionDir)bin\lib\$(ProjectName)_$(ConfigurationName).lib





Pre-Post Build steps:
If you’d like to do some tasks (like copying over something) before or after a build, check out the Build events node under Configuration Properties. I’d recommend against using this.. having this in the build script (e.g. ant or nant) makes it more visible – it tends to get hidden and out of sync in the project properties.

Phew! That's it. Take a nap now to recharge those brain cells.