Rhino Mocks

Rhino Mocks 4.0.0 Alpha Released

It has been a little longer than expected but the latest version of Rhino Mocks has been released and is available from NuGet. You can download the package from here:

https://www.nuget.org/packages/RhinoMocks/4.0.0-alpha

This is an “alpha” release since there are more than likely going to be a few things that come up. As a matter of fact, there are two things that I am already thinking about changing.

One is to be a little more explicit with arranging expectations against properties. Right now when you arrange an expectation against a property the intent is inferred. Instead I think it would be better to be explicit by adding ExpectPropertyGet and ExpectPropertySet.

The other is more of an internal modification to help track expectations easier. Currently an expectation is stored in a single data structure which includes the method, arguments, constraints and return values. When a method is intercepted all of the expectations have to be checked to find a match (clearly there are short circuits but… you get the idea). This modification will help account for how many times a method has (or hasn’t) be called and increase performance.

Until then, however, enjoy this alpha version and feel free to provide feedback.

Advertisements
Standard
Rhino Mocks, xUnit

Fun with xUnit Assert Throws and App Domains

I recently decided to update the shared libraries and tools that are used to build and unit test Rhino Mocks.

I updated psake from version 0.22 to version 4.3.1.0. Now I don’t know about you but that is a significant jump in version number. After the update, no problems. I actually find it easier to deal with and have come to the realization that I should revisit the existing tasks.

I then went ahead and update xUnit from version 1.1.0 to version 1.9.2. After the update I had a significant number of build errors. All of the build errors were concerning the Assert.Throws extension method. In the old version this method had an overload that took a “message” as a parameter. In the latest version this overload was removed.

I was very concerned with this breaking change. There were so many unit tests that used this method to verify the thrown exception message matched the expectation. I cracked open the previous version in dotPeek and took a look at the method. And what I saw was rather surprising.

public static T Throws<T>(string userMessage, ThrowsDelegate testCode)
  where T: Exception
{
  return (T) Throws(typeof(T), testCode);
}

Clearly the userMessage parameter is not being used.

Now realizing that the “message” parameter was never being used. I changed all of the unit tests and removed the messages being passed. After I fixed the unit tests everything was working perfectly. This has now become a fortunate change of events. This now provides me with the ability to change the exception messages to provide better context and more information.

All was right in the world. Well…

It was an hour after the update that I realized that I only updated the xUnit libraries. I hadn’t updated the executable or console application that actually ran the unit tests. So back to NuGet I went to get the latest (stable) version of the xUnit console application.

This is where things took a turn for the worse. There was one (and only one) unit test that was now failing. I am going to give you the namespace and test class name and let you figure out what the problem was: Rhino.Mocks.Test.Remoting.ContextSwitchTests

Talk about fun.

I will save you the gory (and embarrassing) details on how I corrected the problem. The bottom line is that I had to change the way the unit test was creating the App Domain to match the same way the xUnit was loading the unit test into it’s App Domain.

There’s a lesson in here somewhere but right now… I can’t think of it.

Coming up next is documentation and getting the first 4.0.0 alpha build out on NuGet.

Standard
NuGet, Rhino Mocks

Rhino Mocks NuGet

From the beginning of my little adventure I had planned on making sure that Rhino Mocks had a consistent NuGet presence. So it was quite surprising, as I near the end of my first go with revamping Rhino Mocks, that I would get an email about Rhino Mocks package in NuGet. The previous owner of the Rhino Mocks package (Ka-Wai Lin) contacted me to relinquish his ownership and allow me to take it over.

I must confess, at first I was a little wary. A couple of emails later and sure enough… I am now the owner of the Rhino Mocks package in NuGet.

I can’t thank Ka-Wai Lin enough for this generous and gracious offer. Not having to worry about this and being able to keep a consistent presence within NuGet is a huge win.

His Linked-In profile can be found here: http://nl.linkedin.com/pub/ka-wai-lin/0/a34/3a4

Now the *only* thing left to do is get an “alpha” build out there.

Clearly it’s not the only thing left to do but… I’ll leave that for another post

Standard
Rhino Mocks, Unit Testing

Rhino Mocks Final Stretch–Field Problems

The final modifications have been made to the Rhino Mocks code base. It has been interesting working through Properties and Events. What was more interesting, however, were the delegates. Previously these were Callback, Do and WhenCalled and allowed you to pass in a delegate, an Action or a Func to modify the execution flow, change the return value or simply call a delegate. Understanding when to use Callback, Do or WhenCalled was confusing to me so I decided to wrap them up a little differently.

Previously, WhenCalled allowed you to execute an Action that took, as a single parameter, a data structure encapsulating the method invocation. Since an Action was being invoked the return value of the expectation could not be changed.

In the current version, WhenCalled has been modified slightly to simply execute an Action. If the arguments of the calling method are desired then the Action will need to have the same signature of the calling method. One thing that I am continuing to work through is the ability to match the arguments with the parameters of the Action (or delegate) without having to specify all of them. It works but not with “out” or “ref” arguments.

The Callback functionality wasn’t something that I used in the past. The exact reason why this functionality was added is also unknown. From the call signature, unit tests and the way it was executed I can only assume that it was used to validate the arguments of the calling method. This feature has not been brought forward. Not that there isn’t a need but with the available argument constraints I don’t understand the need. If the Callback feature is to ever return it will be re-worded to something like ValidateArgs.

“Do” has been replaced with DoInstead and is meant to allow you to replace the return value from the given Func (or delegate). I don’t particularly like the “Do” notion and may change it to “ReturnInstead.” This may seem like something silly to be considering but the names of the extension methods should reflect their intent as much as possible.

In order to provide a similar feature as the original “WhenCalled”, a new method “Intercept” has been added which expects an Action that takes, as a single parameter, a data structure encapsulating the method invocation. Again, not too certain that I like the name of the method. I also question whether having access to the method invocation is necessary or not. Only time will tell.

I have updated the existing unit tests to use these new constructs over the old and they all pass. So while the code and execution remains the same (or similar), the names of the methods and properly expressing their intent may need some more work.

With all of the “major” unit tests now passing, it is on to the Field Problem unit tests. There are only 104 files to go over so hopefully it will go by quickly. I am hoping that all of them can be converted and pass with limited modification. I have an uneasy feeling, however, that some may need to be removed. It will be important to identify and document what get’s removed in order to speak to them, provide justification and alternatives.

As a side note, someone had asked if this code is on GitHub. The current version that I am working on can be found here:

https://github.com/meisinger/rhino-mocks/tree/innovation

This will get merged into the “master” branch once the Field Problem unit tests have been added (and passing).

Well… back to unit tests…

Standard
Rhino Mocks

Rhino Mocks Expectations for Events

If one of the features I don’t use very often is the Property Behavior then it’s safe to say that I have never (ever) used “events” within Rhino Mocks. I have seen the Raise and GetEventRaiser extension methods in the passed but never used them.

After working through the Property Behavior feature I decided to tackle handling events. I found setting up expectations for events to be really easy. Why? Because there is nothing to them. No really. There is nothing to them at all. The only thing that you can do with events is validate (or expect) subscribing or unsubscribing from an event.

Think about that for a second.

When subscribing to an event you (typically) will use the “+=” assignment operator. When unsubscribing from an event you (typically) will use the “-=” assignment operator. Under the hood you are calling the “add” and “remove” methods respectively but there really isn’t anything you can do beyond that. Both methods are “void” which means there is nothing to return or “mock" to return. Sure, you could throw an exception but I find that to be an extreme edge case that should never be tested. The only other thing you could do is perform a type of callback after subscribing or unsubscribing.

So really, when it comes down to it, the only thing you can do is setup an expectation to validate that an event handler was added or removed. As a part of that expectation you may choose to make the event handler very (very) specific.

The one thing that I don’t like about the current implementation is that you can use null as the event handler when setting up the expectation. Unless you follow that up with a call to the IgnoreArguments method, the expectation will be looking specifically for null to be passed. I can’t tell if this is actually useful to anyone or not. Perhaps instead null can be used to represent anything and thus avoiding the need to call IgnoreArguments.

Just as with the other refinements, there is a new extension method specifically for events named ExpectEvent:

[Test]
public void New_Event_Extension_Method() {
  var mock = Repository.Mock&lt;IConnection&gt;();
  mock.ExpectEvent(x => x.OnShutdown += null);
  ...
  mock.Verify();
}

The options that are returned are greatly reduced. So much so that GetEventRaiser has been removed as well. Right now I am thinking that the Raise extension method works better. And speaking of the GetEventRaiser and the Raise methods (which have not been until now), these methods are simply helper methods for calling the event. Nothing more and nothing less.

Having never used events within Rhino Mocks caused a little bit of delay due to the confusion. The exact things that I am trying to correct are some of the reason for the confusion. By making the extension methods explicit and the" “fluid” interfaces more specific will definitely help.

Up next: Wrapping up.

Standard
Rhino Mocks

Rhino Mocks Property Behavior

One feature that I seldom use in Rhino Mocks is the “Property Behavior.” I remember getting an exception every now and then when I would use a property but never really thought much of it (like I mindless drone I would change the code and run the unit tests again).

In fact, I used properties so infrequently in my unit tests, it wasn’t until I started diving deep into the code that I came to realize there are three “property” based options:

  • PropertyBehavior
  • SetPropertyAndIgnoreArguments
  • SetPropertyWithArgument

After working through the Recursive Mock feature I found that properties are fairly easy to deal with. That is until I tried to setup an expectation for a property based on the value being set.

As it turns out, when a property is used in a delegate the signature has a return value regardless of the operation. This makes thing really difficult to handle when the expectation is being created for a “write-only” property.

The solution has been to create a new type of expectation that handles properties specifically. The expectation captures both the get and set method at the same time. This allows properties to act more like first class expectations without needing to add _special_ extensions.

Granted, to utilize the new expectation you will need to call ExpectProperty rather than Expect. So I guess that is a _special_ extension but… you get the point. There are still some things that need to be considered like whether or not properties should have Repeat options but for the most part it’s done.

One thing that I think is important to point out is the original handling of a property through the Expect method remains the same. It’s only when extra functionality is needed do you need to think about utilizing the ExpectProperty method.

If you’re anything like me, this feature will be useless. Until you need it.

Next up; events…

Standard
Rhino Mocks

Recursive Mocks

I have been going through all of the unit tests for Rhino Mocks attempting to get the first “alpha” release ready. One of the sets of unit tests that were failing (miserably) were the “Recursive Mocks.” I struggled with this for a while. I could implement the feature as intended or simply ignore it and change the unit tests.

Not all of us may know what a Recursive Mock looks like and what the feature enables. Let’s take a quick look at an example. First we will look at how the scenario is commonly implemented followed by the Recursive Mock feature.

The scenario is fairly straightforward and common; two interfaces are being mocked where one of the interfaces contains a method which returns the other interface:

public interface IChannel {
  bool IsOpen();
}

public interface IConnection {
  IChannel CreateChannel(string path);
}

The most common way to mock the IsOpen method is as follows:

[Fact]
public void Scenario_Common_Approach() {
  var connection = Repository.Mock<IConnection>();
  var channel = Repository.Mock<IChannel>();

  channel.Stub(x => x.IsOpen())
    .Return(true);

  connection.Stub(x => x.CreateChannel(Arg<string>.Is.Anything))
    .Return(channel);

  // some interesting test here
}  

With the Recursive Mock feature, however, this scenario could be mocked in the following way:

[Fact]
public void Scenario_Recursive_Approach() {
  var connection = Repository.Mock<IConnection>();

  connection.Stub(x => x.CreateChannel(Arg<string>.Is.Anything).IsOpen())
    .Return(true);

  // some interesting test here
}

While this is a contrived example, what we can see from the Recursive Mock approach is that we don’t need to create a mock for IChannel. Rhino Mocks will actually create a mocked object on-the-fly.

Why would anyone ever use a Recursive Mock?

Imagine what would happen if you had three separate “paths” that you wanted to test. For the first path the IsOpen should return true. For the second path IsOpen should return false. For the third path IsOpen should throw an exception.

That would require three separate IChannel mocked objects (and stubs):

[Fact]
public void Three_Path_Monty() {
  var connection = Repository.Mock<IConnection>();
  var channelOk = Repository.Mock<IChannel>();
  var channelFail = Repository.Mock<IChannel>();
  var channelThrow = Repository.Mock<IChannel>();

  connection.Stub(x => x.CreateChannel("path-ok"))
    .Return(channelOk);

  connection.Stub(x => x.CreateChannel("path-fail"))
    .Return(channelFail);

  connection.Stub(x => x.CreateChannel("path-throw"))
    .Return(channelThrow);

  channelOk.Stub(x => x.IsOpen())
    .Return(true);

  channelFail.Stub(x => x.IsOpen())
    .Return(false);

  channelThrow.Stub(x => x.IsOpen())
    .Throws(new Exception("error"));

  // something interesting
}

The Recursive Mock way… much easier to read:

[Fact]
public void Three_Path_Easy() {
  var connection = Repository.Mock<IConnection>();

  connection.Stub(x => x.CreateChannel("path-ok").IsOpen())
    .Return(true);

  connection.Stub(x => x.CreateChannel("path-fail").IsOpen())
    .Return(false);

  connection.Stub(x => x.CreateChannel("path-throw").IsOpen())
    .Throws(new Exception("error"));

  // something interesting
}

The current version of Rhino Mocks supports this well with the Record and Last Call constructs. With these constructs having been removed in the upcoming version, this feature may be more difficult that what it’s worth. At least that’s what I thought… at first.

My biggest concern was with the fact that in the upcoming version an instance of the expectation is created prior to allowing the interceptor to handle the actual method. With the return types from one method to the next in the chain being different than the return type of the calling delegate I was fearful that my dreams of no state and returning “smart” expectations were lost.

As it turns out this was mitigated through the use of the stack. When a expectation is created it is pushed onto a stack belonging to the mocked object. When the interceptor handles the method call it is able to check the mocked object’s stack for the latest expectation. Implementing the Recursive Mock feature came down to creating the “next” expectation on the fly.

There is a little bit of code clean-up required to make the implementation a little easier to read but beyond that… Recursive Mocking has been implemented.

Next up: Property Behavior.

As it stands right now, this is way more trouble than it’s worth.

Standard