Just Starting with JustMock

A New Mocking Tool

In life, I feel that it’s easiest to understand something if you know multiple ways of accomplishing/using/doing/etc it. Today I decided to apply that reasoning to automatic mocking tools for .NET. I’m already quite familiar with Moq and have posted about it a number of times in the past. When I program in Java, I use Mockito, so while I do have experience with multiple mocking tools, I only have experience with one in the .NET world. To remedy this state of affairs and gain some perspective, I’ve started playing around with JustMock by Telerik.

There are two versions of JustMock: “Lite” and “Elevated.” JustMock Lite is equivalent to Moq in its functionality: able to mock things for which their are natural mocking seems, such as interfaces, and inheritable classes. The “Elevated” version provides the behavior for which I had historically used Moles — it is an isolation framework. I’ve been meaning to take this latter for a test drive at some point since the R&D tool Moles has given way to Microsoft “Fakes” as of VS 2012. Fakes ships with Microsoft libraries (yay!) but is only available with VS ultimate (boo!).

My First Mock

Installing JustMock is a snap. Search for it in Nuget, install it to your test project, and you’re done. Once you have it in place, the API is nicely discoverable. For my first mocking task (doing TDD on a WPF front-end for my Autotask Query Explorer), I wanted to verify that a view model was invoking a service method for logging in. The first thing I do is create a mock instance of the service with Mock.Create<T>(). Intuitive enough. Next, I want to tell the mock that I’m expecting a Login(string, string) method to be called on it. This is accomplished using Mock.Arrange().MustBeCalled(). Finally, I perform the actual act on my class under test and then make an assertion on the mock, using Mock.Assert().

[TestMethod, Owner("ebd"), TestCategory("Proven"), TestCategory("Unit")]
public void Execute_Invokes_Service_Login()
{
    var mockService = Mock.Create<IQueryService>();
    Target = new LoginViewModel(mockService) { Username = "asdf", Password = "fdsa" };
    Mock.Arrange(() =&gt; mockService.Login("asdf", "fdsa")).MustBeCalled();
    Target.Login.Execute(null);

    Mock.Assert(mockService);
}

A couple of things jump out here, particularly if you’re coming from a background using Moq, as I am. First, the semantics of the JustMock methods more tightly follow the “Arrange, Act, Assert” convention as evidenced by the necessity of invoking Arrange() and Assert() methods from the JustMock assembly. The second thing that jumps out is the relative simplicity of assertion versus arrangement. In my experience with other mocking frameworks, there is a tendency to do comparably minimal setup and have a comparably involved assertion. Conceptually, the narrative would be something like “make the mock service not bomb out when Login() is called and later we’ll assert on the mock that some method called login was called with username x and password y and it was called one time.” With this framework, we’re doing all that description up front and then in the Assert() we’re just saying “make sure the things we stipulated before actually happened.”

One thing that impressed me a lot was that I was able to write my first JustMock test without reading a tutorial. As regular readers know I consider this to be a strong indicator of well-crafted software. One thing I wasn’t as thrilled about was how many overloads there were for each method that I did find. Regular readers also know I’m not a huge fan of that. But at least they aren’t creational overloads and I suppose you have to pay the piper somewhere and I’ll have either lots of methods/classes in Intellisense or else I’ll have lots of overloads. This bit with the overloads was not a problem in my eyes, however, as I haven’t explored or been annoyed by them at all — I just saw “+10 overloads” in Intellisense and thought “whoah, yikes!”

Another cool thing that I noticed right off the bat was how helpful and descriptive the feedback was when the conditions set forth in Arrange() didn’t occur:

JustMockFeedback

It may seem like a no-brainer, but getting an exception that’s helpful both in its type and message is refreshing. That’s the kind of exception I look at and immediately exclaim “oh, I see what the problem is!”

Matchers

If you read my code critically with a clean code eye in the previous section, you should have a bone to pick with me. In my defense, this snippet was taken post red-green and pre-refactor. Can you guess what it is? How about the redundant string literals in the test — “asdf” and “fdsa” are repeated twice as the username and password, respectively. That’s icky. But before I pull local variables to use there, I want to stop and consider something. For the purpose of this test, given its title, I don’t actually care what parameters the Login() method receives — I only care that it’s called. As such, I need a way to tell the mocking framework that I expect this method to be called with some parameters — any parameters. In the world of mocking, this notion of a placeholder is often referred to as a “Matcher” (I believe this is the Mockito term as well).

In JustMock, this is again refreshingly easy. I want to be able to specify exact matches if I so choose, but also to be able to say “match any string” or “match strings that are not null or empty” or “match strings with this custom pattern.” Take a look at the semantics to make this happen:

[TestMethod, Owner("ebd"), TestCategory("Proven"), TestCategory("Unit")]
public void Execute_Invokes_Service_Login()
{
    Target = new LoginViewModel(Service) { Username = "asdf", Password = "fdsa" };
    Mock.Arrange(() => Service.Login(
            Arg.IsAny<string>(), 
            Arg.Matches<string>(s => !string.IsNullOrEmpty(s))
        )).MustBeCalled();
    Target.Login.Execute(null);
                
    Mock.Assert(Service);
}

For illustration purposes I’ve inserted line breaks in a way that isn’t normally my style. Look at the Arg.IsAny and Arg.Matches line. What this arrangement says is “The mock’s login method must be called with any string for the username parameter and any string that isn’t null or empty for the password parameter.” Hats off to you, JustMock — that’s pretty darn readable, discoverable and intuitive as a reader of this code.

Loose or Strict?

In mocking there is a notion of “loose” versus “strict” mocking. The former is a scenario where some sort of default behavior is supplied by the mocking framework for any methods or properties that may be invoked. So in our example, it would be perfectly valid to call the service’s Login() method whether or not the mock had been setup in any way regarding this method. With strict mocking, the same cannot be said — invoking a method that had not been setup/arranged would result in a runtime exception. JustMock defaults to loose mocking, which is my preference.

Static Methods with Mock as Parameter

Another thing I really like about JustMock is that you arrange and query mock objects by passing them to static methods, rather than invoking instance methods on them. As someone who tends to be extremely leery of static methods, it feels strange to say this, but the thing that I like about it is how it removes the need to context switch as to whether you’re dealing with the mock object itself or the “stub wrapper”. In Moq, for instance, mocking occurs by wrapping the actual object that is the mocking target inside of another class instance, with that outer class handling the setup concerns and information recording for verification. While this makes conceptual sense, it turns out to be rather cumbersome to switch contexts for setting up/verifying and actual usage. Do you keep an instance of the mock around locally or the wrapper stub? JustMock addresses this by having you keep an instance only of the mock object and then letting you invoke different static methods for different contexts.

Conclusion

I’m definitely intrigued enough to keep using this. The tool seems powerful and usage is quite straightforward, intuitive and discoverable. Look for more posts about JustMock in the future, including perhaps some comparisons and a full fledged endorsement, if applicable (i.e. I continue to enjoy it), when I’ve used it for more than a few hours.

  • http://twitter.com/skimedic Phil Japikse (MVP)

    Erik,

    Nice post! Glad to see you are liking JustMock Lite.
    If you add in Telerik.JustMock.Helpers, all of the mocking calls get exposed as extension methods on your mocks. So you can write:

    mockService.Arrange(x => x.Login(“asdf”, “fdsa”)).MustBeCalled();
    // Other code removed for brevity
    mockService.Assert();

    The choice is your as to which syntax you use, as we fully support both.
    Philip Japikse, MVP, MCSD, CSP
    Developer Evangelist,
    Telerik

  • http://www.daedtech.com/blog Erik Dietrich

    Thanks for the tip! That’s really slick, actually. I definitely like the approach of exposing core functionality and then supporting fluent interfaces via extension methods. I’ve done that myself a few times including my little open source fluent SQL generator. I’ll have to play with both approaches, particularly in the comparison to using Moq, which heavily favors the fluent paradigm.