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.

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<IConnection>();
  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
Rhino Mocks

Am I Just Getting Lazy?

So I have been working on simplifying the Rhino Mock code base for a little while now and have been making good progress. While I have no empirical data yet, I fully expect this simplified code base to be faster and easier to understand.

It has been really interesting watching some of the core concepts shift from being “in your face” to a more subtle “nudge” as the code is simplified. For instance; generating a Strict mock versus a Dynamic, Stub or Partial mock. There are some very important concepts behind choosing the right “type” but what are they and how are they presented?

This has actually caused confusion in the past… and rightly so. A Strict mock is one where any method call that has not had an expectation set will throw an exception. A Dynamic mock is one where only those methods that have had expectations set are verified. Those methods that have no expectations simply return default values. A Stub mock acts just like a Dynamic mock but does not perform any verifications. A Partial mock… well… gives you the ability to call the original method as long as it isn’t abstract (and is virtual of course).

While this is a greatly simplified overview, it identifies a few problems.

In my mind a Strict mock is a verification concern and not a generation (or creation) decision. When expectations are being verified I should have the option to perform the verification strictly or not. The type of mocked object shouldn’t dictate that choice.

[Test]
public void Strict_Verification() {
  var mock = MockRepository.Mock<IPerson>();
  mock.Expect(x => x.GetName())
    .Return("Mike");

  mock.GetName();
  mock.GetAge();

  mock.VerifyExpectations(VerificationType.Strict);
}

In my mind a Stub mock is an expectation concern rather than a generation decision. Either you are setting up an expectation or you are stubbing out the method.

[Test]
public void Stub_A_Stub() {
  var mock = MockRepository.Mock<IPerson>();
  mock.Stub(x => x.GetName())
    .Return("stub?");

  mock.Expect(x => x.GetAge())
    .Return(1);

  mock.GetName();

  mock.VerifyExpectations();
}

If Stub is removed as a “type” of mock object then we also get the added benefit of eliminating the confusion around when to call Expect and when to call Stub. If both Strict and Stub are removed, does Dynamic make any sense?

The Partial mock is the "most correct” decision that needs to be made when creating a mocked object. A Partial mock is a mixture between a concrete class and a derived proxy class that allows me to choose to execute the base method or “mock it away.” A Partial mocked object, however, should be the only type which would expose the CallOriginalMethod method.

[Test]
public void Partial_Person() {
  var mock = MockRepository.Partial<Person>();
  mock.Stub(x => x.CalculatePayRate(Arg<int>.Is.Anything))
    .CallOriginalMethod();

  var rate = mock.CalculatePayRate(35);

  Assert.AreEqual(11.25, rate);
}

Through simplification of the code Rhino Mocks will now only offer two options to create a mocked object: Mock and Partial. None of the core concepts have been removed but they have been muted a little.

The thing I need to figure out now is whether or not I arrived at this decision because I am too lazy to implement those different “types” or because it makes more sense… maybe a little bit of both.

Standard
.Net, Rhino Mocks

Simplifying the Rhino Mocks Code Base

It has been an interesting last couple of days.

I finished converting all of the existing unit tests from using Record/Replay syntax to the Arrange/Act/Assert (AAA) syntax. Oddly enough this lead to a few extra unit tests that were not previously being executed. These newly discovered unit tests could have been removed due to relevance or performance but for whatever reason, they have been added back. I did find that there were a few (eleven in fact) that were no longer relevant and needed to be “skipped.” They are all passing now so… mission accomplished.

With this done I started turning toward the main code base. And… here we go.

Intercepting the Interceptors

Things started out simple enough; moved similar concerns into a different namespace, removed “generated” files minor code corrections. I then moved onto simple refactoring like reducing nesting and leveraging TryGetValue on a Dictionary. Everything was going well. I then started to tackle the interceptors and invocation actions.

If you didn’t already know, Rhino Mocks (as with many other frameworks) utilizes Castle Windsor to create proxies and intercept method calls (via DynamicProxy). This gives us the ability to create proxies for interfaces, delegates and classes that can then have calls intercepted. Some of the methods, however, are from the base System.Object class which everything in the .Net framework inherits. As it turns out, you can actually configure Castle Windsor to ignore these methods. If any method is ignored, however, they are never called which leads to some interesting issues with this like equality and comparison.

Rhino Mocks current solution for this is to intercept these calls and check to see if the method belongs to System.Object. If the method does belong to System.Object then the method is allowed to proceed. This type of “checking” continues for things like properties and events.

I was a little taken back when I came across this. Not because it was being done but how it was being accomplished. As I started to refactor this code I came to the realization that Castle Windsor supports something very similar through something called the IInterceptorSelector interface. When this interface is implemented it allows you to choose which interceptor should handle the method. By adding an implementation of this interface and a few more interceptors, all of the existing code and constructs can be removed.

One Step Forward, Two Steps Back

It would have been great to stop right there. As you might have guessed; that didn’t happen.

After this minor success I turned my focus on the MethodOptions that are returned when you create an expectation. I decided that since the system knew when a Void method was being called there should be no reason to return MethodOptions with a Return method available. Along the same lines, Return method (when it is available) should be allowed to take a Func to return the value.

Diving into this lead me to understand Record/Replay is much more than just a syntax but is the only way Rhino Mocks currently works. When using the AAA syntax, behind the scenes, Rhino Mocks transition the “state” from Replay to Record and back to Replay. Kind of sounds like a lot of steps doesn’t it? Just a tad.

Rather than perpetuating the current approach, a simpler strategy is underway. This strategy does away with the various “states” and puts the onus on the code creating the expectation. The AAA syntax conforms to this nicely since there is really only one way create a expectation. Based on my estimates, this strategy should reduce the code base by around 30 classes. Clearly there will be additional classes added but will be geared towards usability rather than internal plumbing.

I am planning on having a working code set with a majority of the changes completed within the next few weeks. Some of these modifications can be done in the existing code base in which case I’ll cut a minor release. Should be exciting!

Standard