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<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.

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 PencilSharpner 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:

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:

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:

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

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<int> FilterOut(List<int> list, int target)
{
  var myList = new List<int>();
  foreach(int myValue in list)
  {
    if(myValue != target)
    {
       myList.Add(myValue);
    }
  }
  return myList;
}

public void SomeMethod(List<int> 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<int> FilterOut(List<int> list, Func<int, bool> filterCriteria)
{
  var myList = new List<int>();
  foreach(int myValue in list)
  {
    if(!filterCriteria(myValue))
    {
      myList.Add(myValue);
    }
  }
  return myList;
}

public void SomeMethod(List<int> 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

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<IFeatureLocator>().Object;
            return new FeatureResetService(myLocator);
        }

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

            ExtendedAssert.Throws<ArgumentNullException>(() => 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).

By

GitHub and Easy Moq

GitHub

Not too long ago, I signed up for GitHub. I had always used subversion for source control when given the choice, but the distributed nature of Git appealed to me, particularly since I often do work on a variety of different machines. GitHub itself appealed to me because it seemed like the perfect venue for reusable code that I’ve created over the years and tend to bring with me from project to project. Here is a unique idea – sites like Sourceforge want to store code by basic unit of “project” whereas GitHub wants code for the sake of code. This code need not be finished or polished or distributed on any kind of release schedule. That is perfect for a lot of my portable code.

One thing that I noticed about GitHub upon arrival was the lack of .NET work there, compared with other technologies. There is some, but not a lot. Presumably this is because sites like Code Project already offer this kind of thing to the .NET community. After reading about Phil Haack leaving Microsoft to be GitHub’s Windows Ambassador, I decided that this was a good indicator that GitHub was serious about growing that portion of its user base, and that I’d start porting some of my code there.

Another thing that I’d read about git before trying it out was that it has a steep learning curve. To back my general impression of this as a widely held opinion, I did a quick google search and ran across this post.

Given the steep learning curve many (including myself) experience with Git, I think I can safely assume that many other people have this sort of problem with it.

So, there’s at least one person who has experienced a steep learning curve and at least one other person with the same general sense as me about many finding the learning curve steep.

I must say, I haven’t found this to be the case. Perhaps it’s my comfort with Linux command line interaction or perhaps it’s my years of experience using and administering SVN, but whatever it is, I read the GitHub primer and was up and running. And, I don’t mean that I was up and running with commits to my local repository, but I was up and running committing, pushing to GitHub, and pulling that source to a second computer where I was able to build and run it. Granted, I haven’t forked/branched/merged yet, but after a day of using it, I was at the point where the source control system retreated into the mental background where it belongs, serving as a tool I’m taking for granted rather than a mental obstacle (by contrast, even with a couple of years of experience with Rational Clear Case, I still have to set aside extra development time to get it to do what I want, but I digress, since I don’t believe that’s a simple case of needling to mount a learning curve). So, after a day, I’m developing according to my schedule and running a commit when I feel like taking a break and/or a push when I want to update GitHub’s version. I’m sure I’ll be hitting google or StackOverflow here and there, but so far so good.

Easy Moq

So, what am I doing with my first GitHub project? It’s something that I’m calling Easy Moq. I use Moq as my main mocking framework, as I’ve mentioned before, and I’ve had enough time with it to find that I have a certain set of standard setup patterns. Over the course of time, I’ve refined these to the point where they become oft-repeated boilerplate, and I’ve abstracted this boilerplate into various methods and other utilities that I use. Up until now, this has varied a bit as I go, and I email it to myself or upload the classes to my web server or something like that.

But, I’m tired of this hodgepodge approach, and this seems like the perfect use case for trying out GitHub. So, I’m looking over my various projects and my use of Moq and creating my own personal Easy Moq library. If others find it useful, so much the better – please feel free to keep up with it, fork it, add to it, etc.

At the time of writing, I have three goals in mind (these may change as I TDD my way through and start eating my own dog food on real projects). In no particular order:

  • Create Mock inheritors that default to having specific test double behavior – dummies, stubs, spies, etc.
  • Be able to create and use my doubles with the semantics Dummy() or new Spy() rather than new Mock().Object
  • Be able to generate an actual class under test with all dependencies mocked as Dummy, Stub, Spy, etc.

For the first goal, I’ll refer to Niraj’s take on the taxonomy of test doubles. I haven’t yet decided exactly how I’ll define the particular doubles, but the ideas in that post are good background for my aims. Up to this point, if I want to create one of these things with Moq, I instantiate the double in the same fashion and my setup differs. I’d like to make the declaration semantics more expressive — declaring a DummyMock is more expressive as to your intent with the test than creating a Mock and doing nothing else to set it up. For more complicated doubles, this also has the pleasant effect of eliminating manual boilerplate like “SetupAllProperties()”.

For the second goal, this is probably lowest priority, but I’d like to be able to think of the doubles as entities unto themselves rather than wrappers that contain the entity that I want. It may seem like a small thing, but I’m a bit of a stickler (fanatic at times) for clear, declarative semantics.

For the third part, it’d be nice to add a dependency to a class and not have to go back and slaughter test classes with “Find and Replace” to change all calls to new Foo(bar) to new Foo(bar, baz), along with Baz’s setup overhead, particularly when those old tests, by definition, do not care about Baz. I realize that there is already a tool designed to do this (called AutoMoq), but it appears to be for use specifically with Unity. And besides, this is more about me organizing and standardizing my own existing code as well as getting to know GitHub.

So, that’s my first pet project contribution to Git Hub. If anyone gets any mileage out of it, Cheers. :)

Acknowledgements | Contact | About | Social Media