September 24, 2007

NMock as compared to RhinoMocks

At a recent developer group meeting I was asked why we were using Rhino Mocks instead of NMock. He also pointed out that NMock had minor api rewrite that made it nicer to use.

My answer was that Rhino Mocks was standardized before I started with my current team, but I would look into NMock. It never hurts to comparison shop.

So to get get started. If you are not familiar with either framework, I suggest looking at their quick start guides:

Rhino Mocks Quick Start
NMock Quick Start

How to mock an object.

NMock:

Mockery mocks = new Mockery();
IMyInterface aMocked = mocks.NewMock<IMyInterface>();
Rhino Mocks

MockRepository mocks = new MockRepository ();
IMyInterface aMocked = mocks.CreateMock<IMyInterface>();

So far so good, no real difference between them. Rhino Mocks has a minor more typing involved, but frankly, I have code templates for all of that anyway.

Which is better: Tie. They both work just fine.

But lets backup a second. What does IMyInterface look like. This is what we are going to work with:

public interface IMyInterface
{
 int MyProperty { get; set; } 
 int Add(int i, int j); 
 void MyMethod(int i, int j); 
 event EventHandler&lt;EventArgs&gt; MyEvent; 
}

Mock libraries create fake objects to send to your real objects. Your real object can call the fake object's methods and properties, but you have to give the Mocked objects their values (this is called setting expectations). First to note: you aren't testing the mocked object, you are testing the object calling the mocked object.
Anyway, if you need more info on where or when to use a mocked object I'm sure Google will have many excellent examples for you.

OK, so now that we have that part set, lets move on.

Set and get a property:

Quick note: this is telling the mocked object to expect the property to be set to a value. We are not actually setting the value. Also, when we get the property, we have to tell the mock library what to return.

NMock
// set the property
Expect.Once.On(aMock).SetProperty("MyProperty").To(1);
// get the property
Expect.Once.On(aMock).GetProperty("MyProperty").Will(Return.Value (1));
RhinoMock
// set the property
aMock.MyProperty = 1;
// get the property
Expect.Call(aMock.MyProperty).Return(1);

OK, both sets of calls are supposed to be equivalent. The first thing to notice is that whatever typing saving we had in the construction of the mock object has not been completely lost. But I still think amount of typing it takes to do something is somewhat shallow, so lets dig deeper into the syntax.

As you can see, in NMock nothing is implied. The properties setter will be called exactly once, and the value will be retrieved exactly once. In Rhino Mocks, that detail is implied. But more troubling with NMock is the reliance on using strings to specify which property is being called. Where as with Rhino Mocks, you are using the mocked interface itself.

So if I change the name of my property on the interface, both tests will fail. But with Rhino Mocks it will fail at build time, NMock will have to wait for run time. Also, if I'm using Find Usages (a feature of ReSharper) to find every place that MyProperty is being used, it will pick up the Rhino Mocks code, but will not pick up the NMock code. To me that is a usability issue.

Rhino Mocks wins.

Next test: Call a function and return a value; call a method

NMock
Expect.Once.On(aMock).Method("Add").With(1,2).Will(Return.Value(3));
Expect.Once.On(aMock).Method("MyMethod").With(1,2);
Rhino Mock
Expect.Call(aMock.Add(1,2)).Return(3);
aMock.MyMethod(1,2);

The nice thing here is that both libraries are consistent in their approach. I still don't like how you have to specify the method names by a string though. Also, the Will(Return.Value()) does not seem natural to me.

But I do have to nock Rhino Mocks on how it does methods a bit. If there is nothing to return, you just call the method. If there is something to return you use the Expect.Call method. This does not seem as consistent as it should.

Rhino Mocks wins.

Handle multiple calls

This is actually kind of interesting. With the NMock api, specifying multiple calls is actually quite natural, where as Rhino mocks seems like a hack. In NMock the Expect function has the following options:

  • Exactly(int count)
  • AtLeastOnce
  • AtLeast(int count)
  • AtMost(int count)
  • Between(int start, int stop)
  • Never

With Rhino mocks there are two ways to do this, but in both cases you use the Repeat object. Remember if you are calling something that doesn't return a value, you don't have to use the Expect object. So Rhino Mocks adds the LastCall method. LastCall modifies the expectations for the last call you made to a mocked object.

But you are using the Repeat object itself. And here is what you get with that:

  • Any()
  • AtLeastOnce()
  • Once()
  • Twice()
  • Times(int count);
  • Time(int min, int max)
  • Never()

First thing I will note between Rhino Mocks Repeat and NMocks Expect is that they are mostly equivalent. I would like the wording of NMocks Between over the Rhino Mocks Times function though. But, Rhino Mocks is missing the AtLeast(int count) function.

So if I wanted to call both methods of my interface at least 2 times, here is what it would look like.

NMock
Expect.AtLeast(2).On(aMock).Method("Add").With(1,2).Will(Return.Value(3));
Expect.AtLeast(2).On(aMock).Method("MyMethod").With(1,2);
Rhino Mocks
Expect.Call(aMock.Add(1,2).Return(3).Repeat.Times(2, int.Max);
aMock.MyMethod(1,2); LastCall.Repeat.Times(2, int.Max);

As much as I love Rhino Mocks, NMock is the winner on the repeating calls front. The syntax makes more sense and is easier to follow than Rhino Mocks. But to fix Rhino Mocks should be hard. Add an AtLeast function and make it possible to use the Expect function on methods with no return values and I think it is there.

But I still don't completely like NMock as either. I don't like it that you have to set the number of times something is being called before you tell the mock library WHAT is being called. I don't thing that helps readability at all.

Winner: NMock.

Raising Events

All of us have this. Small little routines that are only used when an event is raised. So we need a way to mock the event so we can test that code.

NMock
// First read this article: http://becomingagile.blogspot.com/2007/03/raising-events-in-nmock-20.html
// then do this:
MockEvent myEvent = new MockEvnet();
Expect.Once.On(aMock).EventAdd("MyEvent", Is.Anything).Will(MockEvent.Hookup(myEvent));
myEvent.Raise();
Rhino Mocks
aMock.MyEvent += null;
LastCall.IgnoreArguments();
// tell Rhino mocks not to care who is connecting to event
IEventRaiser eventRaiser = LastCall.GetEventRaiser();
eventRaiser.Raise(null, null); // pass in nulls for both sender and args

Can you raise events in NMock: Yes. Is it directly supported: No.
Can you raise events in Rhino Mock: Yes. Is it directly supported: Yes.

Now working with events can be a bit hard. Working with events on a fake object takes a bit of mental yoga to really make sure you understand what is going on as well. I am not overly ecstatic with how Rhino Mocks does events...but it is supported without doing Google searches and writing another class.

Rhino Mocks wins.

Throwing Exceptions

We also have code that catches exceptions. How often do you test that code? You should. Here is how you do it.

NMock
Expect.Once.On(aMock).Method("MyMethod").With(1,2)
.Will(Throw.Exception(new Exception("Hi There"));
Rhino Mocks
Expect.Call(aMock.MyMethod(1,2)).Throw(new Exception("Hi there");

So again, both do the job. But I still like the Rhino Mocks terseness better.

Rhino Mocks wins.

Summary

In the end I will stick with Rhino Mocks. The Method(string methodName) style still just kills it for me because it breaks compile-time checking, and the fact that you can't set method parameters in a type safe way. If I change a something in an interface I want that to break my build -- even in my test code!

Will NMock do the job: yes. But I still think Rhino Mocks does it better.

September 21, 2007

Rhino Mocks: New syntax

I was browsing though the Rhino Mocks documentation when I found there is an entirely new way to setup a test with mocks.

The old way:

[Test]
public void MyOldTest()
{
// Record your expectations here
Expect.Call(myObject.MyProperty).Return(1);

mocks.ReplayAll();

// do your work here
int i = myObject.MyProperty;

// check you values

mocks.VerifyAll();

Assert.AreEqual(1, i);

}

The new way:

[Test]
public void MyNewTest()
{
// Record your expectations here
using ( mocks.Record() )
{
Expect.Call(myObject.MyProperty).Return(1);
}

// do your work here
int i;
using ( mocks.Playback() )
{
i = myObject.MyProperty;
}

// check you values
Assert.AreEqual(1, i);
}

Now, the most obvious thing about the two code examples is that the new way takes more lines of code. But is that really a valid metric? Not always.

The using statements make a nicer differentiation between the setup and the execution. In the old way, the VerifyAll() method was your differentiator. Sorry, but from four feet back, VerifyAll() just looks like another method. The new way, with the 'with' keyword makes for easier transitions from "what we expect to occur" to "Ok, lets do this thing", and "make sure everything worked as planned."

But wait, there is more!

Now for those of you who think you can NEVER have enough ways to do the same thing, and think that anonymous delegates are the GREATEST THING EVER! There is something for you too.

It is the With statement which gives you a fluent interface (which is all the rage on the blogosphere these days). Anyway, it looks like this:

int i;
With.Mocks(mocoks).Expecting( delegate
{
// Record your expectations here
Expect.Call(myObject.MyProperty).Return(1);
})
.Verify(delegate
{
// do your work here
i = myObject.MyProperty;
}
}
// check you values
Assert.AreEqual(1, i);

Now normally I am all in favor of fluent interfaces. SubSonic, LINQ, and Lambda are all great examples of this. But I worry that the fluent style interface is trying too hard in this case.

That said, sometime soon I'll probably see a use for it and it will be wonderful. But until then.

So now you have seen three ways of doing the same thing with one mocking library. That should be enough to keep everyone busy for a while.

September 20, 2007

No Silverlight for you

There are always problems to be found when dealing with new technologies. Currently, I'm playing with Silverlight.

My first project with silverlight was to convert my header (the flaming computer at the top of the page) to a silverlight header. Rev one would be a straight, look alike, conversion of the existing header. The only really cool part is that I would be able to change the text on the header. I can't do that right now because all of the text is an image.

And I did it. It works beautifully...except on my blog. All I get from there is a blank box.

A bit of digging with FireBug and it appears my web host is blocking all xaml files. And you know you are in for a bad day when you call support and they say "What is xaml?" Answer: it is just like Flash.

Oh well, they are supposed to get back to me today. We will see how that goes.

If you want, check out my sample page. Hopefully it will be working in the next day or two.

September 13, 2007

2 Days in Boise

These are two pictures I took one day apart in Boise, ID. Both pictures were taking in the morning.

Sept 6 is the bottom picture, Sept 7 is the top picture.

The top picture, from Sept 7, is what I would consider a hazy day in Boise.

The bottom is about as bad as it gets. On days like that you can really smell the smoke in the air. That is the type of day that you see asthma sufferers looking for their inhalers.

Now I know that my blog has a reference to fire on it...but this really isn't what I was referring to.

September 11, 2007

Boise MSDN Event on Oct 4

Thursday, October 04, 2007 1:00 PM - Thursday, October 04, 2007 5:00 PM Mountain Time (US & Canada)
Welcome Time: 12:00 PM

Theater - Edwards Boise Stadium 21

7701 Overland Road
Boise Idaho 83709
United States

Language(s):
English.

Product(s):
ASP.NET, Office, Visual Studio and Windows Vista.

Audience(s):
Developer.

Event Overview

MSDN Events are free, live sessions designed to enhance your coding skills and make your life a little easier. By attending you’ll get up –to-the-minute technology delivered by seasoned developers and have lots of time to network and ask questions. Chat with your fellow developers get the latest coding tools and tips and learn how to create rich new applications. Register today for a free live event in your area and get the hands on knowledge you need. For more information visit: http://www.msdnevents.com.

September 05, 2007

JQuery is just cool

I've had the opportunity to play around with JQuery
a bit these days. I'm not exactly a Javascript expert by any means, but
JQuery is just cool -- and a bit odd. We know that Javascript is a functional
language, but it does have some object-like stuff you can do with it as well.
But everything is still a function. JQuery has it's own function that you use to
access everything in it as well. The function is $. I'm not kidding, it is $.
Instead of a JQuery function, we have the function formally known as JQuery now
called $. Just wonderful. Then you find out it plugs into the CSS classes. What
now? How the heck? But a typical script you will write looks like this:

$(document).ready(function(){
$("a").filter(".clickme").click(function(){alert("Hi there");}).end() });

Here is what is going on with that statement:

  1. (first $) Find the document node, set a function to the ready() function (that
    lets you know everything is loaded)

  2. (second $) Find any link ( <a>) with a css classes named "clickme" (e.g.
    <a class="clickme">)

  3. Override that links click function.

  4. When the link is click display "Hi there" to the user in a message box


So what you can do with that silly $ is pretty darn cool. Plus there are
plug-ins for it. I have an ASP.Net GridView on my form. In this case I can
display all of the data on the grid without paging or anything special. But I
want to sort the data. There is a JQuery plug-in called
TableSorter that you can use. This will
sort any table with a theader tag. Which would normally work fine as is, but the
GridView doesn't output a theader tag without some modifications. The following
C# does the trick (note: did not come up with this code, I found it on
DotNetSlackers):

private void MakeGridAccessible(GridView grid)
{
if (grid.Rows.Count > 0)
{
grid.UseAccessibleHeader = true;
grid.HeaderRow.TableSection = TableRowSection.TableHeader;
grid.FooterRow.TableSection = TableRowSection.TableFooter;
}
}

Use that function right after you load your data into your gridview. Next you
need to setup your javascript. You have to include JQuery.js, and
jquery.tablesorter.pack.js, then call tablesorter on your table via javascript.
This works for a GridView named grdData:


<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.tablesorter.pack.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#grdData").tablesorter();
}
);
</script>
And done. Really, that is it. We are done. You can click on any of the headers
on the grid and the grid resorts itself. No other fussing, no ajax calls to get
more data. I like it.