DaedTech

Stories about Software

By

Improving Readability using Moq

While I’ve been switching a lot of my new projects over to using JustMock, as explained here, I still have plenty of existing projects with Moq, and I still like Moq as a tool. One of the things that I have struggled with in Moq that JustMock provides a nice solution to is the cognitive dissonance that arises when thinking about how to reason about your test doubles.

In some situations, such as when you’re injecting the test doubles into your class under test, you want them to appear as if they were just another run of the mill instance of whatever interface/base you’re passing. But at other times you want to configure the mock, and then you want to think of them as actual mock objects. One solution to that is to use Mock.Get() as I described here. Doing that, you can store a reference to the object as if it were any other object but access it using Mock.Get() when you want to do things to its setup:

[gist id=”4998372″]

That’s all well and good, but, perfectionist that I am, I got really tired of all of that Mock.Get() ceremony. It makes lines pointlessly longer, and I think really detracts from the readability of the test classes. So I borrowed an idea from JustMock with its “Helpers” namespace and created a series of extension methods. Some examples are shown here.

[gist id=”4998277″]

These extension methods allow me to alter my test to look like this:

[gist id=”4998488″]

Now there’s no need to switch context, so to speak, between mock object and simple dependency. You always have a simple dependency that just so happens to have some extension methods that you can use for configuration. No need to keep things around as Mock<T> and call the Object property, and no need for all of the Mock.Get().

Of course, there are caveats. This might already exist somewhere and I’m out of the loop. There might be issues with this that I haven’t yet hit, and there is the debugging indirection. And finally, you could theoretically have namespace collisions, though if you’re making methods called “Setup” and “Verify” on your classes that take expression trees and multiple generic parameters, I’d say you have yourself a corner case there, buddy. But all that aside, hopefully you find this useful–or at least a nudge in a direction toward making your own tests a bit more readable or easy to work with.

By

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();
Target = new LoginViewModel(mockService) { Username = "asdf", Password = "fdsa" };
Mock.Arrange(() => 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(),
Arg.Matches(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.

By

Mock.Of() and Mock.Get() in Moq

Today, I’d like to highlight a couple of features of Moq that I didn’t know about until relatively recently (thanks to a recent google+ hangout with Moq author, Daniel Cazzulino). Since learning about these features, I’ve been getting a lot of mileage out of them. But, in order to explain these two features and the different paradigm they represent, let me reference my normal use of Moq.

Let’s say we have some class PencilSharpener that takes an IPencil and sharpens it, and we want to verify that this is accomplished by setting the Pencil’s length and sharpness properties:

public void Sharpen_Sets_IsSharp_To_True()
{
    var myPencilDouble = new Mock();
    myPencilDouble.SetupProperty(pencil => pencil.IsSharp);
    myPencilDouble.Object.IsSharp = false;
    myPencilDouble.SetupProperty(pencil => pencil.Length);
    myPencilDouble.Object.Length = 12;

    var mySharpener = new PencilSharpener();
    mySharpener.Sharpen(myPencilDouble.Object);

    Assert.IsTrue(myPencilDouble.Object.IsSharp);
}

So, I create a test double for the pencil, and I do some setup on it, and then I pass it into my sharpener, after which I verify that the sharpener mutates it in an expected way. Fairly straight forward. I create the double and then I manipulate its setup, before passing its object in to my class under test. (Incidentally, I realize that I could call “SetupAllProperties()”, but I’m not doing that for illustrative purposes).

But, sometimes I’d rather not think of the test double as a double, but just some object that I’m passing in. That is, perhaps I don’t need to invoke any setup on it, and I just want to reason about the actual proxy implementation, rather than stub.object. Well, that’s where Mock.Of<>() comes in:

[TestMethod, Owner("ebd"), TestCategory("Proven"), TestCategory("Unit")]
public void Sharpen_Sets_IsSharp_To_True()
{
    var myPencil = Mock.Of();
    myPencil.IsSharp = false;

    var mySharpener = new PencilSharpener();
    mySharpener.Sharpen(myPencil);

    Assert.IsTrue(myPencil.IsSharp);
}

Much cleaner, eh? I never knew I could do this, and I love it. In many tests now, I can reason about the object not as a Mock, but as a T, which is an enormous boost to readability when extensive setup is not required.

Ah, but Erik, what if you get buyer’s remorse? What if you have some test that starts off simple and then over time and some production cycles, you find that you need to verify it, or do some setup. What if we have the test above, but the Sharpen() method of PencilSharpener suddenly makes a call to a new CanBeSharpened() method on IPencil that must suddenly return true… do we need to scrap this approach and go back to the old way? Well, no, as it turns out:

[TestMethod, Owner("ebd"), TestCategory("Proven"), TestCategory("Unit")]
public void Sharpen_Sets_IsSharp_To_True()
{
    var myPencil = Mock.Of();
    myPencil.IsSharp = false;
    Mock.Get(myPencil).Setup(pencil => pencil.CanBeSharpened()).Returns(true);

    var mySharpener = new PencilSharpener();
    mySharpener.Sharpen(myPencil);

    Assert.IsTrue(myPencil.IsSharp);
}

Notice the third line in this test. Mock.Get() takes some T and grabs the Mock containing it for you, if applicable (you’ll get runtime exceptions if you try this on something that isn’t a Mock’s object). So, if you want to stay in the context of creating a T, but you need to “cheat”, this gives you that ability.

The reason I find this so helpful is that I tend to pick one of these modes of thinking and stick with it for the duration of the test. If I’m creating a true mock with the framework — an elaborate test double with lots of customized returns and callbacks and events — I prefer to instantiate a new Mock(). If, on the other hand, the test double is relatively lightweight, I prefer to think of it simply as a T, even if I do need to “cheat” and make the odd setup or verify call on it. I find that this distinction aids a lot in readability, and I’m taking full advantage. I realize that one could simply retain a reference to the Mock and another to the T, but I’m not really much of a fan (though I’m sure I do it now and again). The problem with that, as I see it, is that you’re maintaining two levels of abstraction simultaneously, which is awkward and tends to be confusing for maintainers (or you, later).

Anyway, I hope that some of you will find this as useful as I did.

By the way, if you liked this post and you're new here, check out this page as a good place to start for more content that you might enjoy.

By

Introduction to C# Lambda Expressions

Today, I’m going to post an excerpt of a tutorial I created for the use of Moq on an internal company wiki for training purposes. I presented today on mocking for unit tests and was revisiting some of my old documentation, which included an introductory, unofficial explanation of lambda expressions that doesn’t involve any kind of mathematical lingo about lambda calculus or the term “first class functions”. In short, I created this to help someone who’d never or rarely seen a lambda expression understand what they are.

Lambdas


Since Moq makes heavy use of lambda expressions, I’ll explain a bit about how those work here. Lambdas as a concept are inherently highly mathematical, but I’ll try to focus more on the practical aspects of the construct as they relate to C#.

In general, lambda expressions in the language are of the form (parameters) => (expression). You can think of this as a mapping and we might say that the semantics of this expression is “parameters maps to expression”. So, if we have x => 2*x, we would say “x maps to two times x.” (or, more generally, number maps to number).

In this sense, a lambda expression may be thought of in its most practical programming sense as a procedure. Above, our procedure is taking x and transforming it into 2*x. The “maps to” semantics might more colloquially be called “becomes”. So, the lambda expression x => 2*x translates to “x becomes 2 times x.”

Great. So, why do this? Well, it lets you do some powerful things in C#. Consider the following:

public List FilterOut(List list, int target)
{
  var myList = new List();
  foreach(int myValue in list)
  {
    if(myValue != target)
    {
       myList.Add(myValue);
    }
  }
  return myList;
}

public void SomeMethod(List values)
{
  var myNewList = FilterOut(values, 6);  //Get me a list without the sixes.
}

Here, we have a function that will filter an int value out of a list. It’s a pretty handy function, since it lets you pick the filter value instead of, say, filtering out a hard-coded value. But, let’s say some evil stakeholder comes along and says “well, that’s great, but I want to be able to filter out two values. So, you add a method overload that takes two filters, and duplicate your code. They then come along and say that they want to be able to filter out three values, and they also want to be able to filter out values that are less than or greater than a specified value. At this point, you take a week off because you know your code is about to get really ugly.

Except, lambda expressions to the rescue! What if we changed the game a little and told the stakeholder, “hey, pass in whatever you want for criteria.”

public List FilterOut(List list, Func<int, bool> filterCriteria)
{
  var myList = new List();
  foreach(int myValue in list)
  {
    if(!filterCriteria(myValue))
    {
      myList.Add(myValue);
    }
  }
  return myList;
}

public void SomeMethod(List values)
{
  var myNewList = FilterOut(values, x => x == 6);  //Get me a list without the sixes.
  myNewList = FilterOut(values, x => x == 6 || x == 7); //Get me a list without six or seven.
  myNewList = FilterOut(values, x => x > 6 && x < 12); //Get me a list with no values between 7 and 11.
 //... and anything else you can think of that takes an integer and returns a boolean
}

Now, you don’t have to change your filter code at all, no matter what the stakeholder asks for. You can go back and say to him, “hey, do whatever you want to that integer — I don’t care”. Instead of having him pass you an integer, you’re having him pass you something that says, “integer maps to bool” or “integer becomes bool”. And, you’re taking that mapping and applying it to each element of the list that he’s passing you. For elements being filtered out, the semantics is “integer becomes false” and for elements making the cut “integer becomes true”. He’s passing in the mapping, and you’re doing him the service of applying it to the elements of the list he’s giving you.

In essence, lambda expressions and the mappings/procedures that they represent allow you to create algorithms on the fly, ala the strategy design pattern. This is perfect for writing code where you don’t know exactly how clients of your code want to go about mapping things — only that they do.

As it relates to Moq, here’s a sneak peak. Moq features expressions like myStub.Setup(mockedType => mockedType.GetMeAnInt()).Returns(6);
What this is saying behind the scenes, is “Setup my mock so that anyone who takes my mocked type and maps it to its GetMeAnInt() method gets a 6 back from it” or “Setup my mock so that the procedure MockedType.GetMeAnInt() returns 6.”

(By the way, the link I used for the visual is from this post, which turned out to be a great find. RSS feed added to my reader.)

By the way, if you liked this post and you're new here, check out this page as a good place to start for more content that you might enjoy.

By

Poor Man’s Automoq in .NET 4

So, the other day I mentioned to a coworker that I was working on a tool that would wrap moq and provide expressive test double names. I then mentioned the tool AutoMoq, and he showed me something that he was doing. It’s very simple:

 [TestClass]
    public class FeatureResetServiceTest
    {
        #region Builders

        private static FeatureResetService BuildTarget(IFeatureLocator locator = null)
        {
            var myLocator = locator ?? new Mock().Object;
            return new FeatureResetService(myLocator);
        }

        /// If you're going out of your way to pass null instead of empty, something is wrong
        [TestMethod, Owner("ebd"), TestCategory("Proven"), TestCategory("Unit")]
        public void ResetToDefault_Throws_NullArgumentException()
        {
            var myService = BuildTarget();

            ExtendedAssert.Throws(() => myService.ResetFeaturesToDefault(null));
        }

The concept here is very simple. If you’re using a dependency injection scheme (manual or IoC container), your classes may evolve to need additional dependencies, which sucks if you’re declaring them inline in every method. This means that you need to engage in a flurry of find/replace, which is a deterrent from changing your constructor signature, even when that’s the best way to go.

This solution, while not perfect, definitely eliminates that in a lot of cases. The BuildTarget() method takes an optional parameter (hence the requirement for .NET 4) for each constructor parameter, and if said parameter is not supplied, it creates a simple mock.

There are some obvious shortcomings — if you remove a reference from your constructor, you still have to go through all of your tests and remove the extra setup code for that dependency, for instance, but this is still much better than the old fashioned way.

I’ve now adopted this practice where suitable and am finding that I like it.

(ExtendedAssert is a utility that I wrote to address what I consider shortcomings in MSTest).