Jul 30, 2010

Mocking Comparison – Part 9: Functions

Let’s say you’ve got a mock object and you want a method on your mock to do something with a particular method that goes beyond just returning a specified value.  What do you do?  Why, you use a function of course!  When you stub a method call on a mock you simply tell the mock object to call a method or use a lambda to calculate the return value rather than just returning a specified value.

Let’s have a look at how Rhino Mocks, Moq and NSubstitute do this.

What we’re going to do is supply some simple methods that our mock object will use when we call certain methods so that we can dynamically alter the return value from the CurrentFleaCount method and we’ll then assert that the value has changed.

Rhino Mocks

[Fact]
public void Rhino_functions_and_callbacks()
{
var fleaCount = 25;
var monkey = MockRepository.GenerateMock<IMonkey>();

monkey.Stub(m => m.CurrentFleaCount()).Do(new Func<int>(() => fleaCount));
monkey.Stub(m => m.TryAddFleas(1)).IgnoreArguments()
.Do(new Func<int, bool>(fleas =>
{
fleaCount = fleas;
return true;
}));

Assert.Equal(25, monkey.CurrentFleaCount());

monkey.TryAddFleas(10);
Assert.Equal(10, monkey.CurrentFleaCount());
}

Since this is a reasonable chunk of code, let’s just look at the key parts.  When we stub the CurrentFleaCount method call we tell it to use a function that takes no arguments, and use the value of the fleaCount variable (defined in the test) to figure out what returns.

You may ask why didn’t we just do a .Return(fleaCount) like we normally would? Simple answer: we want to get the value to change as the test progresses.  By using a Func<T> means that the return value is calculated each time we call the stubbed method, rather than just having a single fixed value returned for every call.

Similarly in the stubbed TryAddFleas() method, we are providing a function that takes one parameter and returns a boolean.  Our stub method simply changes the value of fleaCount variable so that the next CurrentFleaCount() call will return a different value, and this is what the Asserts are checking for.

Hopefully that makes sense.  Form a day to day usage viewpoint it’s not something you do that often but when you need the functionality it’s really useful.

Moq

[Fact]
public void Moq_functions_and_callbacks()
{
var fleaCount = 25;
var monkey = new Mock<IMonkey>();

monkey.Setup(m => m.CurrentFleaCount()).Returns(() => fleaCount);
monkey.Setup(m => m.TryAddFleas(It.IsAny<int>()))
.Returns<int>(fleas =>
{
fleaCount = fleas;
return true;
});

Assert.Equal(25, monkey.Object.CurrentFleaCount());

monkey.Object.TryAddFleas(10);
Assert.Equal(10, monkey.Object.CurrentFleaCount());
}

The Moq syntax is much the same as the Rhino syntax, as you can see.  It’s probably a little nicer in that you use the same Returns() method to either return fixed values or call a function, unlike Rhino Mocks where you have to use the .Do() method.

It also doesn’t require the creation of new Func<T> objects – you just supply the method body you wish to use, which means less code.

NSubstitute

[Fact]
public void Nsubstitute_functions_and_callbacks()
{
var fleaCount = 25;
var monkey = Substitute.For<IMonkey>();

monkey.CurrentFleaCount().Returns(args => fleaCount);
monkey.TryAddFleas(Arg.Any<int>())
.Returns(args =>
{
fleaCount = (int)args[0];
return true;
});

Assert.Equal(25, monkey.CurrentFleaCount());

monkey.TryAddFleas(10);
Assert.Equal(10, monkey.CurrentFleaCount());
}

The NSubstitute code is a little different to the others in that instead of having parameter lists to deal with you are passed a single array containing all the parameters and it’s up to you to pull out the ones you wish to use and cast them as required by your test.

This has it’s advantages in that you avoid code littered with arguments you never use, but it has a downside in that you need to cast every parameter you do use.  That said, just like Moq, you get to use the same Returns() method for either returning a fixed value or supplying a method and you don’t need to create new Func<T> objects so the code isn’t noisy.  And better than Moq is it’s overall cleaner syntax, as we have seen in many of the previous posts.

My preference? NSubstitute.  The casting of parameters is a little annoying, but it doesn’t have Moq .Object. tax and this is one of the few times you’ll actually see a lambda in a test using NSubstitute.

 

Other posts in this series:

How To: Versioning Builds With TFS 2010

I’ve written in the past on how to do automatic assembly versioning with TFS Team Build 2008 so it’s about time I got around to showing you how to do with with TFS Team Build 2010.

By the way, for a great series of blog posts on customising team build with TFS 2010 it’s worth having a look at Ewald Hofman’s series on customising team build.

What We Want to Achieve

So, the goal here is to change the standard build process to enable us to do automatic versioning of assemblies.  To do this what we need to do is insert some steps in the process just after the source has been retrieved from TFS.  We want a flow that goes something like this:

Get Latest –> Update AssemblyInfo files with new version –> Do rest of the build

One extra wrinkle to this is that when team build gets the code from TFS the files are in read only mode, so what we’re going to do is switch the read only flag off, change the files, and then turn it back on.  This is just in case an future incremental get tries to update the file – the read only flag will stop TFS checking if the file is different.

One thing we’re not going to do is check the updated assembly info files back into source control.  This means all developer builds will by default have a version number of 1.0.0.0 and build server builds will have an incrementing build number.  It’s a handy way to know if someone has tried to deploy code built on their machine instead of code built by the server.

This approach does raise a small issue though – where do we keep the build number between builds?  i.e. how to we know what the previous build number was so we can increment it.  For this we’re going to use a simple version.txt file stored in the root of the drop folder.  If you want to secure this so that only the build process updates the version number I would suggest making the drop location read only for all users except the account the build runs under.

Anyway, enough talk.  Let’s see what we need to do.

Getting Started

1. Open VS2010 and create a solution with two C# Class LIbrary projects in it.  One for the custom build tasks we’re going to create, and one to hold the process template we’re going change.  I have called mine CustomBuildActivities and CustomBuildProcess

2. In the CustomBuildProcess project add a Workflow activity and then delete it.  This just helps with getting a bunch of references in place and adds the appropriate content type we’ll need when we add our build workflow in the next step.

image

3. Now go copy the DefaultTemplate.xaml file, rename it to something you like and include it in your project.  I’ve called mine VersionedBuildProcess.xaml.  Once it’s included in the solution change the Build Action to XamlAppDef.

image

At this point if you try compiling you’ll get a bunch of missing references, so add the following (sorry it’s a laundry list of items!)

  • System.Drawing
  • Microsoft.TeamFoundation.Build.Client
  • Microsoft.TeamFoundation.VersionControl.Client
  • Microsoft.TeamFoundation.WorkItemTracking.Client
  • %Program Files%\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\
    Microsoft.TeamFoundation.Build.Workflow.dll
  • %Program Files%\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\
    Microsoft.TeamFoundation.TestImpact.BuildIntegration.dll
  • %WinDir%\assembly\GAC_MSIL\Microsoft.TeamFoundation.TestImpact.Client
    \10.0.0.0__b03f5f7f11d50a3a\Microsoft.TeamFoundation.TestImpact.Client.dll

UPDATE: If you set the Build Action to None then you don't need to worry about setting all those references and you can still edit the XAML as per usual. This is a lot easier for many people, but the downside is that you can't verify the workflow is 100% correct unless you manually look through the whole workflow or try a build with it. My preference is the first, but do whatever you're comfortable with :-)

Create the First Custom Activity

Next  we’re going to create our first custom activity – this one will be the one we use to toggles the read only flags on AssemblyInfo files.  In your CustomBuildActivities project add a new Workflow Code Activity called SetReadOnlyFlag.  We’ll use this to toggle the read only bits for our AssemblyInfo files later on.

image

Now add references to Microsoft.TeamFoundation.Build.Client and Microsoft.TeamFoundation.VersionControl.Client and then use the following code for the class:

using System.Activities;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.VersionControl.Client;

namespace CustomActivities
{
[BuildActivity(HostEnvironmentOption.Agent)]
public sealed class SetReadOnlyFlag : CodeActivity
{
[RequiredArgument]
public InArgument<string> FileMask { get; set; }

[RequiredArgument]
public InArgument<bool> ReadOnlyFlagValue { get; set; }

[RequiredArgument]
public InArgument<Workspace> Workspace { get; set; }

protected override void Execute(CodeActivityContext context)
{
var fileMask = context.GetValue(FileMask);
var workspace = context.GetValue(Workspace);
var readOnlyFlagValue = context.GetValue(ReadOnlyFlagValue);

foreach (var folder in workspace.Folders)
{
foreach (var file in Directory.GetFiles(folder.LocalItem, fileMask, SearchOption.AllDirectories))
{
var attributes = File.GetAttributes(file);
if (readOnlyFlagValue)
File.SetAttributes(file, attributes | FileAttributes.ReadOnly);
else
File.SetAttributes(file,attributes & ~FileAttributes.ReadOnly);
}
}
}
}
}

The [BuildActivity] attribute on the class indicates that this class can be used as a workflow activity in the designer, and that it should be loaded on the build agent when a build runs.

This code here is how we define the arguments that the activity will use – they will appear in the properties window when the activity is selected in the designer, and the RequiredAttribute indicates that these properties must have values for the workflow to be valid.

[RequiredArgument]
public InArgument<string> FileMask { get; set; }

[RequiredArgument]
public InArgument<bool> ReadOnlyFlagValue { get; set; }

[RequiredArgument]
public InArgument<Workspace> Workspace { get; set; }

We’re going to use the Workspace to get information about where the build agent has physically put files on the disk so that we can get path information and search for the files we wish to change.  The other properties are used to actually find out what files to change and which way to set the flag.

Create The Second Custom Activity

For this activity we want to take a set of files as defined by a mask and do a search/replace on them to update the version numbers for the AssemblyVersion and AssemblyFileVersion attributes.

Here’s the code:

[BuildActivity(HostEnvironmentOption.Agent)]
public sealed class UpdateAssemblyVersionInfo : CodeActivity
{
[RequiredArgument]
public InArgument<string> AssemblyInfoFileMask { get; set; }

[RequiredArgument]
public InArgument<string> SourcesDirectory { get; set; }

[RequiredArgument]
public InArgument<string> VersionFilePath { get; set; }

[RequiredArgument]
public InArgument<string> VersionFileName { get; set; }

protected override void Execute(CodeActivityContext context)
{
var sourcesDirectory = context.GetValue(SourcesDirectory);
var assemblyInfoFileMask = context.GetValue(AssemblyInfoFileMask);
var versionFile = context.GetValue(VersionFilePath) + @"\" + context.GetValue(VersionFileName);

//Load the version info into memory
var versionText = "1.0.0.0";
if (File.Exists(versionFile))
versionText = File.ReadAllText(versionFile);
var currentVersion = new Version(versionText);
var newVersion = new Version(currentVersion.Major, currentVersion.Minor, currentVersion.Build + 1, currentVersion.Revision);
File.WriteAllText(versionFile, newVersion.ToString());

bool changedContents;
foreach (var file in Directory.EnumerateFiles(sourcesDirectory, assemblyInfoFileMask, SearchOption.AllDirectories))
{
var text = File.ReadAllText(file);
changedContents = false;
// we want to find 'AssemblyVersion("1.0.0.0")' etc
foreach (var attribute in new[] { "AssemblyVersion", "AssemblyFileVersion" })
{
var regex = new Regex(attribute + @"\(""\d+\.\d+\.\d+\.\d+""\)");
var match = regex.Match(text);
if (!match.Success) continue;
text = regex.Replace(text, attribute + "(\"" + newVersion + "\")");
changedContents = true;
}
if (changedContents)
File.WriteAllText(file, text);
}
}
}

At this point you should be able to compile your application and see it all pass, but until we change the workflow itself this is pretty useless.

Updating the Build Workflow

In your process project open up the build process.  In the toolbox you should now see something like this:

image

We want to drop these tasks into our workflow at the appropriate point, so to do this find the part of the workflow that looks something like this:

image

For reference it’s in ….Sequence > Run On Agent > Initialize Workspace (near the bottom)

Now add a sequence activity after the get workspace activity like so:

image

Change the display name property to “Update AssemblyInfo Versions"” or something similar.  This not only appears in the build log, but has the advantage of helping you understand your workflow better.

Now drag the ReadOnly flag activity we created into the new sequence activity you added – it should now look something like this:

image

That error indicator means we haven’t yet supplied some property values for the activity, so we’d best do that now.

Set Activity Properties

If you look at the properties window for our activity you should see something like this:

image

What we want is for the users of our workflow to be able to specify the values for the FileMask via the Build Definition window, and we want to set the values for the Workspace based on whatever is current in our workflow.

Let’s tackle the FileMask first.  To do this we’re going to add a new Argument to our overall workflow.  Find the Arguments tab at the bottom of the designer:

image

Click in the Create Argument box and add a new argument called AssemblyInfoMask and give it a default value of “AssemblyInfo.*”

Before we use this in our activities let’s just make a few more changes to make this argument appear in the build process window the way we want it.  Go to the metadata argument a few lines above and click the ellipsis […] button.  You will see a window appear where we can set values that will let Visual Studio know how to display this argument to the end user.  Let’s do just that:

image

Now let’s fix the properties on our Activity

image

Now you may be asking where the Workspace value comes from since it’s not an argument for the workflow.  If you look a few activities above you will see a create workspace activity and one of it’s properties is an OutProperty called Result:

image

This is where the Workspace variable is created.  Unfortunately there’s not really an easy way of tracking this sort of thing with the workflow, but fortunately most variables in the workflow are well named and you should be able to figure out what most of them do.

Finishing the Workflow

Let’s finish off the workflow.  Drag the UpdateAssemblyVersionInfo task into the workflow along with a second SetReadOnlyFlag task.

Before we set the properties on these, we’re going to need one more workflow Argument, being the name of the version file we’re going to store the version information in.

image

Don’t forget to set the Metadata as well so that it appears in the correct place in Visual Studio when we define builds.

Now set the properties on the UpdateAssemblyVersionInfo activity as follows:

image

Since we want to store the file we hold our version info at the root of the drop location we have set the VersionFilePath to BuildDetail.DropLocationRoot.  You can of course, change this to put it wherever you like.

Finally set the properties for the second SetReadOnlyFlag task, this time with the ReadOnly flag set to true.

At this point build your project.  If it’s all OK everything should compile and you should be ready for the next step.

Using The New Build Process

Before we can use the new build process, we have to ensure both the process and the custom activities are in source control.

The .xaml process file should be added to the BuildProcessTemplates folder, and I usually place custom activities in a subfolder within that.  For example:

image

Now we have to tell our Build Controller where to find our custom activities otherwise the build will fail.  Go to Manage Build Controllers…

image

and in the properties window set the path to the activities

image

Now we can finally create a build definition.

In the new build definition window, go to the Process tab, select the Show Details window and Click New..

image

Select an existing .xaml file (being the new process you uploaded)

image

If you set your metadata properties correctly, the process settings should now look something like this:

image

If all goes well, you should get a completed build and see something like the following in the log, indicating our new steps occurred.

image

Finally go to the drop location, right click one of your assemblies and see that the version information is being updated.

Phew! That’s it!  We’re done!

I know it’s a fair bit of work getting this all set up, but once you’ve done it once and have your initial workflow project in place, you can use it as the basis for any future process customisations which makes things much quicker.  Also as you get more familiar with the workflows themselves and knowing where to make changes the process customisation itself will also become faster and easier.

Good luck customising your builds!

Jul 29, 2010

Mocking Comparison – Part 8: Recursive Mocks

Recursive mocks (or nested mocks as some people call them) are a feature of the mocking frameworks where they will automatically create mock objects for items they should return if you reference a property or method of that object when setting up expectations.  The advantages of doing this are that we have less “arrange” code in our test classes and can focus our efforts more on our act and assert code.

Maybe that explanation of recursive mocks doesn’t clarify things much for you so let’s just look at some code instead and see how Rhino Mocks, Moq and NSubstitute help us out.

Rhino Mocks

[Fact]
public void Rhino_recursive_mocks()
{
var monkey = MockRepository.GenerateStub<IMonkey>();
monkey.Name = "Spike";
monkey.Stub(m => m.Keeper().AssignedMonkey).Return(monkey);
Assert.NotNull(monkey.Keeper());
Assert.Equal("Spike", monkey.Keeper().AssignedMonkey.Name);
}

If you have a look at the code you can see that we create a stub object for the the IMonkey interface.  Within that we set up an expectation that when we check which monkey the keeper is assigned to that it should be the monkey object we just created (i.e. we’re setting up a circular object reference).

We don’t need to create a specific IZooKeeper stub object here as Rhino will do that for us and if you step through the test in debug mode you can see that we have a fake object created for us:

image

Moq

The code for Moq is much the same apart from the fact that we have to set up the property behaviour for the monkey’s name and remember if we’re dealing with the mock or the object it’s returning.

[Fact]
public void Moq_recursive_mocks()
{
var monkey = new Mock<IMonkey>();
monkey.Setup(m => m.Keeper().AssignedMonkey).Returns(monkey.Object);
monkey.SetupProperty(m => m.Name);
monkey.Object.Name = "Spike";
Assert.NotNull(monkey.Object.Keeper());
Assert.Equal("Spike", monkey.Object.Keeper().AssignedMonkey.Name);
}

Interestingly, if you look at the code in the final assert closely you’ll see that the mock/object distinction is lost when we start using the recursive mocks.  Instead of using Keeper().Object.AssignedMonkey we just have Keeper().AssignedMonkey.  It’s not a big deal, but it seems to break the paradigm that Moq has used elsewhere of separating the Mock from the object itself.

NSubstitute

And finally the NSubstitute approach

[Fact]
public void Nsubstitute_recursive_mocks()
{
var monkey = Substitute.For<IMonkey>();
monkey.Keeper().AssignedMonkey.Returns(monkey);
monkey.Name = "Spike";
Assert.NotNull(monkey.Keeper());
Assert.Equal("Spike", monkey.Keeper().AssignedMonkey.Name);
}

Nice and clean.  No lambdas. Expressive and direct.  What more could you want :-)

P.S. At time of writing the recursive behaviour was only available when building from source.

 

The verdict? NSubstitute is the clear winner here.

 

Other posts in this series:

How To “Remember My Password” with TFS 2010

If you connect to a TFS server with a machine that isn’t in the same domain then you will typically see something like this:

image

So you click the Use different credentials button to login and get a dialog that looks the this. But wait! Where’s the “Remember my password” checkbox?!

image

It’s not there!  It’s OK, don’t panic. There is a way to avoid entering your credentials every time you want to connect.

In Windows 7 you can use the Credential Manager feature as follows.  Head to the control panel and click the Credential Manager icon.

image

Next click the “Add a Windows credential” link:

image

Then enter your details.  Not that the network address is just the machine name of the TFS server you are connecting to.

image

And you’re done!  Go back to Visual Studio, connect to TFS again and you won’t have any more login prompts.  Yay!

For the Windows XP/Vista users you will need to go to Control Panel -> User Accounts -> Manage your Network Passwords instead.  The UI is a little different, but it should be fairly self-evident..

P.S. For the observant amongst you wondering why my machine is TFS2008-VM when this is a post about TFS2010, it’s because I’m using an upgraded TFS2008 instance.  It’s definitely a TFS2010 machine :-)

Jul 28, 2010

Mocking Comparison – Part 7: Exceptions

One of the great benefits of using mocks in your tests is being able to check how your classes behave when exceptions are thrown.  You do test for this sort of thing, right? :-)

Let’s say we have a persistence mechanism that talks to SQL.  What happens when we get a SQL primary key violation?  What if we are talking to web services and the connection drops or we get some other WCF exception?  How do we handle that?

More importantly, how do we get Rhino Mocks, Moq or NSubstitute to raise those exceptions.  Let’s have a look.

Rhino Mocks

[Fact]
public void Rhino_throwing_exceptions()
{
var monkey = MockRepository.GenerateMock<IMonkey>();
monkey.Stub(m => m.Name).Throw(new ApplicationException());
Assert.Throws<ApplicationException>(() => monkey.Name);
}

This is pretty simple code.  Instead of returning a value, just throw an exception when the method is called.  Too easy!

Moq

[Fact]
public void Moq_throwing_exceptions()
{
var monkey = new Mock<IMonkey>();
monkey.Setup(m => m.Name).Throws(new ApplicationException());
Assert.Throws<ApplicationException>(() => monkey.Object.Name);
}

The Moq code is much the same as the Rhino code, except we still have that .Object. tax that annoys me so much.

NSubstitute

[Fact]
public void Nsub_throwing_exceptions()
{
var monkey = Substitute.For<IMonkey>();
monkey.Name.Returns(args => { throw new ApplicationException(); });
Assert.Throws<ApplicationException>(() => monkey.Name);
}

Not quite as clean as the other two frameworks here, though I’m sure the guys will rectify this soon enough.

 

And the winner: Rhino Mocks. Even though Moq requires slightly less code than Rhino it’s .Object. distinctions will always annoy me.

 

Other posts in this series:

Jul 27, 2010

Bad Keyboard Design

I have to wonder at times what goes through designer’s heads and wether they use their own products.  Have a look at the following keyboard for a HP machine I’ve been given to use when on site.

IMG_0089

Look at the size of that Shift key on the left there. The thing is about half it’s normal size, which of course means I keep hitting the key next to it far too often and screwing up my typing.  I have to train my hands to perform more finger gymnastics than is normal, and can’t easily slide my left thumb into position like I normally would (maybe I shouldn’t use my thumb for shift, but it’s a habit I’ve picked up from gaming and it’s hard to overcome).

But  maybe there’s a reason why they did it.  A reason why they cut the left shift key in half but kept the right hand one full sized?  Oh, there’s it is! It’s so they could add an extra (and duplicated) key on the keyboard! I for one know that the backslash and pipe characters are easily the most commonly used ones in my arsenal.  On my laptop the backslash key is so worn away from use I can hardly make out the symbols on it any more.  It’s worse than even the ‘e’ and return keys!  Thank goodness keyboard usability was sacrificed to add an extra one of those puppies!  Thank you HP! Thank you!

OK. Rant over.  Time to go steal a keyboard from someone else in the office, and while I do that why don’t you let me know what the most annoying keyboard design is that you’ve used or seen?

Jul 26, 2010

Mocking Comparison – Part 6: Multiple Calls

Our comparison of Rhino Mocks, Moq and NSubstitute continues with a look at how multiple calls to a mock are handled and what you do if you want to alter the return values on subsequent calls.

Consider the scenario where you have a method you’re calling that you want to be successful the first time you call it, but where subsequent calls should fail (such as trying to save the same data twice, etc).  How do you do this?

Rhino Mocks

In Rhino Mocks to set return values for multiple calls to a method you simply specify the return value that many times.  To avoid duplication of code you can use the repetition syntax we saw in Part 5.

[Fact]
public void Rhino_multiple_calls()
{
var monkey = MockRepository.GenerateMock<IMonkey>();

monkey.Stub(m => m.TryAddFleas(1)).Return(true).Repeat.Twice();
monkey.Stub(m => m.TryAddFleas(1)).Return(false);

Assert.True(monkey.TryAddFleas(1));
Assert.True(monkey.TryAddFleas(1));
Assert.False(monkey.TryAddFleas(1));
}

Given that we have set up the return value 3 times, what happens when we make the call a fourth time?  At this point Rhino Mocks, having exhausted it’s known set of return values, will start returning the default value.

What if you just want to return the value True for every call?  We would use the Repeat.Any() method as shown here:

[Fact]
public void Rhino_multiple_calls()
{
var monkey = MockRepository.GenerateMock<IMonkey>();

monkey.Stub(m => m.TryAddFleas(1)).Return(true).Repeat.Any();

Assert.True(monkey.TryAddFleas(1));
Assert.True(monkey.TryAddFleas(1));
}

Moq

Moq doesn’t have a nice way of defining mixed return values (not that I can find anyway) however you can implement the same thing using callbacks, which we’ll cover in a later post.

By default setting a return value on a method call will always return that value no matter how many times it is called, so we can at least do the following:

[Fact]
public void Moq_multiple_calls()
{
var monkey = new Mock<IMonkey>();
monkey.Setup(m => m.TryAddFleas(1)).Returns(true);

Assert.True(monkey.Object.TryAddFleas(1));
Assert.True(monkey.Object.TryAddFleas(1));
}

NSubstitute

The code for mixed return values in NSubstitute is so nice.  To handle multiple calls providing different return values you can just provide multiple values or use an array in the return statement as follows:

[Fact]
public void Nsubstitute_multiple_calls()
{
var monkey = Substitute.For<IMonkey>();

monkey.TryAddFleas(1).Returns(true,true,false);

Assert.True(monkey.TryAddFleas(1));
Assert.True(monkey.TryAddFleas(1));
Assert.False(monkey.TryAddFleas(1));
}

And if you just want to always return true, then it works just like Moq does (with the benefit of not requiring the .Object. tax in the assert statements:

[Fact]
public void Nsubstitute_multiple_calls()
{
var monkey = Substitute.For<IMonkey>();

monkey.TryAddFleas(1).Returns(true);

Assert.True(monkey.TryAddFleas(1));
Assert.True(monkey.TryAddFleas(1));
}

If you can’t tell, my decision on the best framework to choose goes to NSubstitute.  It has such a simple and elegant way to handle both requirements, and again, not a single lambda in site.  Excellent!

 

Other posts in this series:

Jul 23, 2010

Mocking Comparison - Part 5: Repetitions

In Part 4 we looked at how parameter constraints are handled and in Part 3 we looked at how to do interaction based tests with mocks.  In this part we bring those two pieces together and add a little extra to check if a call was made a specific number of times.

Let’s just jump straight into the code shall we?

Rhino Mocks

Our test here is simply going to call a method a number of times and verify that the call was made the correct number of times using constraints to verify the correct calls.  It’s a completely useless test, other than as a vehicle to show you how to do this sort of thing

[Fact]
public void Rhino_repetitions()
{
var monkey = MockRepository.GenerateMock<IMonkey>();

monkey.TryAddFleas(5);
monkey.TryAddFleas(-1);
monkey.TryAddFleas(9);

monkey.AssertWasCalled(m => m.TryAddFleas(0),
options => options.Constraints(
Is.GreaterThan(3) && Is.LessThanOrEqual(10)
)
.Repeat.Twice());
monkey.AssertWasCalled(m => m.TryAddFleas(-1),
options => options.Repeat.Once());
}

Note the important part, the .Repeat.Twice() and .Repeat.Once() calls.  It’s these calls that define our expectations as to how many times the call should have been made.

Rhino also features a .Repeat.Time(n) call you can use as well if once or twice don’t cut it for you.

Moq

[Fact]
public void Moq_repetitions()
{
var monkey = new Mock<IMonkey>();

monkey.Object.TryAddFleas(5);
monkey.Object.TryAddFleas(-1);
monkey.Object.TryAddFleas(9);

monkey.Verify(m => m.TryAddFleas(
It.IsInRange(3,10,Range.Exclusive)
),
Times.Exactly(2));
monkey.Verify(m => m.TryAddFleas(-1), Times.Once());
}

Instead of using the word Repeat, Moq uses Times.  Apart from that there is little difference.

NSubstitute

Unfortunately NSubstitute doesn’t support this feature yet as it’s still a maturing framework.  If you really need to do this type of testing then you’ve got a few options – use Rhino or Moq, contribute to the NSubstitute project, or to just not do this type of testing :-).

Interaction based testing is valid at times, but it’s generally brittle and is usually a sign of “implementation verifying” tests rather than behaviour/specification verifying tests (but that’s an argument for another time)

 

Verdict: Moq wins out in this case simply because it’s constraint system is more terse than the Rhino one, but this is purely a personal taste thing.

 

Other posts in this series:

Jul 22, 2010

Mocking Comparison – Part 4: Parameter Constraints

Continuing with our comparison of Rhino Mocks, Moq and NSubstitute we now turn our eye to how constraints are managed.

Consider a method with parameters that was want to mock.  By default, a mock object will only return a specified value if the parameters passed to it exactly match the call signature specified to the mock object.  Maybe that’s a bit wordy, so as a quick example if you say Method(“a”).Returns(“Fred”) you’ll only get “Fred” back from the mock when you pass “a” as the parameter.  Passing “b” gets you nothing. Make sense?

OK, so what if I then want my mock object to provide different return values when different parameter values are used.  How do we avoid writing too much code or having to work out exactly what we should expect as a parameter every time?  And what if I don’t care what’s passed in, I just want a return value.

This is where constraints come into play.  Let’s look at some code to show how it works:

Rhino Mocks

Here’s a test where we try to add fleas to our monkey.  Adding positive numbers of fleas should succeed and adding a negative number of fleas should fail.

[Fact]
public void Rhino_no_constraints()
{
var monkey = MockRepository.GenerateMock<IMonkey>();
monkey.Stub(m => m.TryAddFleas(5)).Return(true);
monkey.Stub(m => m.TryAddFleas(-1)).Return(false);
monkey.Stub(m => m.TryAddFleas(9)).Return(true);

Assert.Equal(true, monkey.TryAddFleas(5));
Assert.Equal(false, monkey.TryAddFleas(-1));
Assert.Equal(true, monkey.TryAddFleas(9));
}

Notice how the use of explicit parameter values in the stubs means we have to repeat a lot of code.  Hmm, that’s annoying.

Thankfully we can simplify this by just ignoring the arguments as seen in the code below.  Note that we still have to supply a parameter value for the TryAddFleas lambda in the Stub call, even though it’s ignored.

[Fact]
public void Rhino_ignore_arguments()
{
var monkey = MockRepository.GenerateMock<IMonkey>();
monkey.Stub(m => m.TryAddFleas(0)).IgnoreArguments().Return(true);

Assert.Equal(true, monkey.TryAddFleas(5));
Assert.Equal(false, monkey.TryAddFleas(-1));
Assert.Equal(true, monkey.TryAddFleas(9));
}

However this will now cause the test to fail because we no longer return a false when passed -1 as a value.

So what we really want is to only return true when the argument value is in a certain range.  For fun let’s make that range between 4 and 9 inclusive.  Here’s the test now, using constraints:

[Fact]
public void Rhino_constraints()
{
var monkey = MockRepository.GenerateMock<IMonkey>();

monkey.Stub(m => m.TryAddFleas(0))
.Constraints(Is.LessThan(10) && Is.GreaterThan(3))
.Return(true);
Assert.Equal(true, monkey.TryAddFleas(5));
Assert.Equal(false, monkey.TryAddFleas(-1));
Assert.Equal(true, monkey.TryAddFleas(9));
}

Whilst this means I have 2 less Stub calls to make, it does tend to be a little verbose.  Expressive, but verbose.  For those wondering why I don’t have a constraint for the -1 argument, I’m relying on the standard behaviour of mocks.  If a constraint isn’t matched then the standard mock behaviour is to return the default value of the return type, being false in this case.

Moq

Here’s the same thing in Moq.  For brevity and completeness I’ve included a commented out line that shows what you would do if you just wanted to ignore parameter values

[Fact]
public void Moq_constraints()
{
var monkey = new Mock<IMonkey>();

//monkey.Setup(m => m.TryAddFleas(It.IsAny<int>())).Returns(true);
monkey.Setup(m => m.TryAddFleas(It.IsInRange(3, 10, Range.Exclusive)))
.Returns(true);
Assert.Equal(true, monkey.Object.TryAddFleas(5));
Assert.Equal(false, monkey.Object.TryAddFleas(-1));
Assert.Equal(true, monkey.Object.TryAddFleas(9));
}

The IsInRange method is quite nice, and the range constraints can be either inclusive or exclusive, however the code feels as verbose if not more so than the Rhino approach.

Note that if you use a test harness like MSpec (Machine.Specifications) then the “It” static class that Moq uses clashes with the “It” class used by MSpec for defining specifications which makes writing code a little painful at times.

NSubstitute

Finally the NSubstitute version.

[Fact]
public void Nsubtitute_constraints()
{
var monkey = Substitute.For<IMonkey>();

//monkey.TryAddFleas(Arg.Any<int>()).Returns(true);
monkey.TryAddFleas(Arg.Is<int>(count => count > 3 && count < 10))
.Returns(true);

Assert.Equal(true, monkey.TryAddFleas(5));
Assert.Equal(false, monkey.TryAddFleas(-1));
Assert.Equal(true, monkey.TryAddFleas(9));
}

This works much the same as the others with the difference being that you have a predicate as the parameter and you need to supply the parameter type to the Arg.Is<T> call.

From a readability perspective, there’s less code which is good and it’s easier to read than the other frameworks because of it’s terseness.  As a bonus, using the Arg.Any<T> call means we can avoid lambdas completely..

 

Verdict: I’ll go with the NSubstitute version as my first choice, though it’s more a matter of style choice than anything else. After that I prefer the Moq syntax over Rhino in this case.

 

Other posts in this series:

Jul 21, 2010

Mocking Comparison – Part 3: Interactions

Our comparison of Rhino Mocks, Moq and NSubstitute continues with a look at how these frameworks support interaction based testing (whether that’s a good idea or not is not going to be dealt with here!).

The idea behind interaction based testing is checking if our class under test makes appropriate calls to the mocked objects.  Typically this is done when testing against API’s that want things done in a certain order or where you want to check that the Save method of a repository was called, as an example.

For our example code we’re going to be testing that the Keeper makes the appropriate call to check the current flea count and then, because the flea count is low, does not try and clean the monkey, i.e. Monkey.Clean() should not be called.

Note that code for the classes under test is in Part 1 of this series.

Rhino Mocks

[Fact]
public void Rhino_method_was_called()
{
var monkey = MockRepository.GenerateMock<IMonkey>();
var keeper = new ZooKeeper {AssignedMonkey = monkey};
monkey.Stub(m => m.CurrentFleaCount()).Return(0);

keeper.CleanMonkey();

monkey.AssertWasCalled(m => m.CurrentFleaCount());
monkey.AssertWasNotCalled(m => m.Clean());
}

So in the initial arrange section of our test we stub out the CurrentFleaCount() call to return zero fleas when called.

We then perform the Act part of our test and ask the Keeper to clean the monkey.

Finally in the Assert part of our test we check if the monkey had methods called on it – the CurrentFleaCount method should be called, and the Clean method should not be called.

If you’re playing along at home, you may have noticed that changing the monkey’s flea count to 100 still makes the test pass, when we should have expected the test to fail (because the clean method should now be called).  This won’t happen because there is a second guard clause in the keeper’s CleanMonkey() method that checks if the monkey is awake and this will always return false.

It brings up an important point with all mock objects in that the default response for any method not explicitly stubbed out is to return the default value, and the default for a bool is false.

Moq

[Fact]
public void Moq_method_was_called()
{
var monkey = new Mock<IMonkey>();
var keeper = new ZooKeeper() {AssignedMonkey = monkey.Object};

monkey.Setup(m => m.CurrentFleaCount()).Returns(0);

keeper.CleanMonkey();

monkey.Verify(m => m.CurrentFleaCount());
monkey.Verify(m => m.Clean(), Times.Never());
}

The code here is similar to Rhino’s code however you’ll notice that to configure our mock object in Moq we use Setup instead of Stub/Expect calls to set the return behaviour for the flea count method.

Moq uses a single Verify method to check that a call was made, so to check that something wasn’t called you have to check that it was called zero times – expressed in Moq syntax as Times.Never().  Make your own mind up over whether this is clear enough from a readability perspective, but I find that it feels a little like Yoda has been writing code and the Verify call seems like it should have a boolean statement for its parameter, not be asserting that a method was called.

NSubstitute

[Fact]
public void Nsubstitute_method_was_called()
{
var monkey = Substitute.For<IMonkey>();
var keeper = new ZooKeeper { AssignedMonkey = monkey };
monkey.CurrentFleaCount().Returns(0);

keeper.CleanMonkey();

monkey.Received().CurrentFleaCount();
monkey.DidNotReceive().Clean();
}

Firstly, not the lack of lambda methods anywhere in this code.  The mock object behaviour is setup by simply attaching a .Returns(0) to the monkey.CurrentFleaCount() method making the code more expressive and simpler to read.

As far as the asserts are concerned we check that a call was Received() by our mock object or that the mock DidNotReceive() the call.  I find this syntax better than the other frameworks in that there’s no lambdas, but it doesn’t read quite as well as I might like.

 

The verdict: It’s a split decision between Rhino and NSubstitute, with me wanting the best of both.

 

Other posts in this series:

Jul 20, 2010

Mocking Comparison – Part 2: Properties

Carrying on with our Rhino Mocks, Moq and NSubstitute comparison, let’s now look at how the various frameworks handle properties on their mock objects.

Rhino Mocks

So in RhinoMocks you have two choices for creating mock objects – using GenerateMock<T>() or GenerateStub<T>().  GenerateMock will create a mock object that tracks calls made to it so that you can assert expectations against which calls were made at the end of your test.  GenerateStub on the other hand creates a stub object, which is to all intents and purposes the same as a mock object just without any of the overhead for tracking which calls were made against it.  In other words you can do asserts to check if a call was made on a mock, but not on a stub.

Why does this matter?  Because properties on mocks and stubs have different default behaviours in RhinoMocks.

For a mock object we have to explicitly indicate if we want a property to have a standard getter/setter applied to it (i.e. just like an autoproperty implementation).  Here’s some code

[Fact]
public void Rhino_properties()
{
var monkey = MockRepository.GenerateMock<IMonkey>();
monkey.Stub(m => m.Name).PropertyBehavior();

monkey.Name = "Spike";
Assert.Equal("Spike", monkey.Name);
}

and the same test with a stub

[Fact]
public void Rhino_properties()
{
var monkey = MockRepository.GenerateStub<IMonkey>();

monkey.Name = "Spike";
Assert.Equal("Spike", monkey.Name);
}

Note that the stubbed object requires none of the property behaviour setup and so it feels more natural.  While some people may prefer to see properties being set up explicitly rather than implicitly I think that if it is a well known behaviour then it’s not going to be a problem that the property behaviour is implicitly provided on the stubbed objects.

Moq

The Moq code is much the same, however as you can see we have to pay the Moq .Object. tax on our calls.

[Fact]
public void Moq_properties()
{
var monkey = new Mock<IMonkey>();
monkey.SetupProperty(m => m.Name);

monkey.Object.Name = "Spike";
Assert.Equal("Spike", monkey.Object.Name);
}

This makes the code feel just a little more verbose and cumbersome than the Rhino and NSubstitute versions.

In fairness, if you want all properties to be automatically set to the standard autoproperty behaviour for a mock object you can use the SetupAllProperties method in Moq as follows:

[Fact]
public void Moq_properties()
{
var monkey = new Mock<IMonkey>();
monkey.SetupAllProperties();

monkey.Object.Name = "Spike";
Assert.Equal("Spike", monkey.Object.Name);
}

NSubstitute

The NSubstitute code shown below is much the same as the Rhino Mocks code when using stubs.  The difference being that NSubstitute doesn’t differentiate between stubs and mocks.

[Fact]
public void NSubstitute_properties()
{
var monkey = Substitute.For<IMonkey>();

monkey.Name = "Spike";
Assert.Equal("Spike", monkey.Name);
}

Overall, Rhino and NSubstitute are on par, however the more expressive mock object creation and reduced confusion over whether to use mocks or stubs in NSubstitute tilts the balance in favour of NSubstitute.

 

Other posts in this series:

Mocking Comparison – Part 1: The Basics

I recently gave a talk on mocking at the DDD Sydney conference called “You Look Like A Monkey and You Smell Like One Too”.  In it I not only got to call the audience various names and get mocked in return, but I also showed a number of features of mock frameworks and how they can be used.  Essentially it was a comparison of a number of mock frameworks, with a particular focus on a few of the main open source ones out there and a great new comer – specifically RhinoMocks, Moq and NSubstitute.

This is part 1 of series running through the code I had on screen and providing some thoughts on the pros and cons of each framework in the context of the scenario I’m showing.  This first part will be longer than the others simply because we have to put some ground work in place.  So, let’s stop wasting time and get started…

What Are We Testing?

All right, so in order to do any mocking we really should have an application to test.  For the purposes of this series the code is a simple class library.  It does nothing useful in the real world, but it does give us something to test.  It’s a pseudo “zoo” featuring monkeys, zoo keepers and tourists.

The IMonkey Interface

Every zoo needs a monkey, and thus we need a monkey right? Of course we do! However, because the monkeys haven’t been tested yet,  the monkeys aren’t yet on display (or at least we haven’t written the code for them yet) so all we have to interact with for now is an IMonkey interface as follows:

public interface IMonkey
{
string Name { get; set; }
bool TryAddFleas(int numberOfFleas);
int CurrentFleaCount();
void Clean();
bool IsAwake(DateTime timeOfDay);
void BananaReady(object sender, BananaEventArgs e);
event EventHandler<EventArgs> Dance;
IZooKeeper Keeper();
}

The IZooKeeper Interface and the ZooKeeper

Monkeys have Keepers, and since all staff in any organisation are just “resources” and thus completely interchangeable (grrr – don’t get me started on this kind of thinking!) we should have an IZooKeeper interface.  We are also lucky enough to actually have a standard ZooKeeper definition as well.  Here’s the code:

public interface IZooKeeper
{
event EventHandler<BananaEventArgs> OnBananaReady;
IMonkey AssignedMonkey { get; set; }
void CleanMonkey();
void FeedMonkeys();
}
public class ZooKeeper : IZooKeeper
{
public event EventHandler<BananaEventArgs> OnBananaReady;

public IMonkey AssignedMonkey { get; set; }

public void CleanMonkey()
{
if (AssignedMonkey == null) return;
if (AssignedMonkey.CurrentFleaCount() < 10) return;
if (AssignedMonkey.IsAwake(DateTime.Now))
AssignedMonkey.Clean();
}

public void FeedMonkeys()
{
if (OnBananaReady != null)
{
OnBananaReady(this, new BananaEventArgs(true));
}
}
}

public class BananaEventArgs : EventArgs
{
public BananaEventArgs(bool isRipe)
{
IsRipe = isRipe;
}

public bool IsRipe { get; private set; }
}

Tourists!

Every zoo needs tourists, and in this case we want concrete instances of tourists, not just some definition of what a tourist should be.  Our tourists are a little weird in that every tourist that comes to our zoo expects our monkeys to dance, and should that happen then they’ll take a photo.  Here’s the code:


public class Tourist
{
IMonkey monkey;

~Tourist()
{
if (monkey!= null)
monkey.Dance -= Look_ADancingMonkey;
}

public int PhotosTaken { get; private set; }

public void SeeAMonkey(IMonkey monkey)
{
if (this.monkey != monkey && this.monkey != null)
this.monkey.Dance -= Look_ADancingMonkey;

this.monkey = monkey;
monkey.Dance += Look_ADancingMonkey;
}

public void Look_ADancingMonkey(object sender, EventArgs args)
{
if (((IMonkey)sender).CurrentFleaCount() <= 100)
{
TakeAPhoto((IMonkey)sender);
}
return;
}

private void TakeAPhoto(IMonkey monkey)
{
PhotosTaken++;
Console.WriteLine(monkey.Name);
}
}

Record/Replay Is Dead

OK.  That’s done, now let’s get into it.  If you’ve used a mocking framework in previous years you may have used Record/Replay syntax.  The idea being you record the steps you want your mock to perform, then switch to replay mode, do the steps again and assert everything worked.  Here’s what Record/Replay looks like using Rhino Mocks in an XUnit test harness:


private string testName = "Spike";

[Fact]
public void Rhino_record_replay()
{
var repository = new MockRepository();
var monkey = repository.StrictMock<IMonkey>();

//In record mode at the moment
Expect.Call(monkey.Name).Return(testName);

//Now in replay mode
repository.ReplayAll();
var actual = monkey.Name;

Assert.Equal(testName, actual);
}

As you can see, we create a MockRepository object, ask the repository to give us a new mock object for a, call the method we want to mock out once, set the expected return value, then we switch to Replay mode and make the call again before finally doing our assertions.

From the small sample code you may be forgiven for thinking that the code isn’t all that bad, however the fact that you have to think about what mode you’re takes you out of the mode of thinking about what it is you’re actually meant to test, and that’s not a good thing. To make matters worse, this is a simple case.  When you get into complex cases, record/replay is downright painful and the amount of repeated code that has to happen in order to set up expectations is often overwhelming and confusing.

Oh, you’ll also notice that the sample code is using a StrictMock.  If this is what you’re doing, then stop it! StrictMocks are a great way to make your tests brittle and hard to maintain and should be avoided wherever possible.  Just search for why strict mocks are bad on your favourite search engine and you’ll no doubt find more information about it.

Use Arrange Act Assert Instead

Let’s now look at the same code using Rhino Mocks in AAA syntax mode.  In case you’re not aware of this, AAA syntax is a way of structuring the tests where you Arrange any pre-requisites for the test, Act on the class under test and then Assert that things occurred as expected.

[Fact]
public void Rhino_arrange_act_assert()
{
//Arrange
var monkey = MockRepository.GenerateMock<IMonkey>();
monkey.Stub(m => m.Name).Return(testName);

//Act
var actual = monkey.Name;

//Assert
Assert.Equal(testName, actual);
}

As you can see, the code is simpler, structured more cleanly and is also easier to read.  In large test libraries this makes things much more maintainable, which is a good thing.

The Moq Version

So far the code has used the Rhino Mocks framework.  Another very popular framework is Moq.  Here’s what the same test in Moq looks like:

[Fact]
public void Moq_arrange_act_assert()
{
var monkey = new Mock<IMonkey>();
monkey.Setup(m => m.Name).Returns(testName);

var actual = monkey.Object.Name;

Assert.Equal(testName, actual);
}

Moq became popular when it was released because no other test framework could do what it did in terms of setting up expectations via lambdas and providing such an easy way of performing AAA style tests.

Over time the other frameworks have caught up, and for me personally, the fact that Moq has a distinct delineation between the mock and the object being mocked (i.e. the monkey.Object code) adds clutter to the test code that I don’t like.  Others like that clarity, but I personally find it just gets in the way.

On the other hand, mock object creation is far less verbose, which is a good thing.

NSubstitute

Finally, the new kid on the block.  NSubstitute’s code looks like the following:

[Fact]
public void Nsubstitute_arrange_act_assert()
{
var monkey = Substitute.For<IMonkey>();
monkey.Name.Returns(testName);

var actual = monkey.Name;

Assert.Equal(testName, actual);
}

What you see is that the code is much terser than Rhino and Moq.  A mock is created as a “substitute for” a IMonkey and we don’t need to use lambdas to set return values for a mocked property, greatly improving readability of the test code and making test code feel more expressive.

My preference of the three for the basic syntax and coding? NSubstitute.

 

Other posts in this series:

Jul 12, 2010

How to Tell ReSharper Underscores Are OK For Tests

Here’s the scenario – you use ReSharper and you want to use BDD style naming in your tests. You know; that style with all those underscores in the test names so that your really long test names are actually readable.  The problem is, ReSharper get’s all upset at you when you do this and throws warnings in your face something like this:

image

Now you could always turn that rule off, but that would mean losing the benefit of picking up bad names in the rest of your code which is not ideal.  What you really want is the best of both worlds (cue Hannah Montana intro music – gah! I blame my 10 year old for that. Sorry).

Anyway, here’s how to configure ReSharper to allow underscores:

Go to ReSharper->Options->Naming Style.  Highlight the Method naming rule and click Edit.

image

Click the Add button and add in a new rule for First_upper as shown here:

image

Now go back and look at your source… It be blue squiggle free. Yay!

image

By the way, if you want to have use naming such as Upper_Case_And_Underscores then you’re out of luck as far as I can tell, since there’s no options I can see to add a new name style to R#.

Jul 6, 2010

Cleaner Mocking with NSubstitute

Rhino Mocks is a great mocking framework, being seen as one of the best ones around and rightly so, however it’s syntax at times is a little verbose and clunky.

A few of the guys from the Sydney Alt.Net group who work together at Cochlear got a little fed up with the syntax Rhino uses for creating and managing mocks and figured there must be a better way.  A different approach that will give them much cleaner code.  As a result they’ve gone and created a project to produce a clean API for mocking and released it as an open sourced project called NSubstitute.

For example, consider the following two code samples:

[Fact]
public void Rhino_MethodWasCalled()
{
var monkey = MockRepository.GenerateMock<IMonkey>();
var keeper = new ZooKeeper {AssignedMonkey = monkey};
monkey.Stub(m => m.CurrentFleaCount()).Return(0);

keeper.CleanMonkey();

monkey.AssertWasCalled(m => m.CurrentFleaCount());
monkey.AssertWasNotCalled(m => m.Clean());
}

versus the equivalent test in NSubstitute

[Fact]
public void NSubstitute_MethodWasCalled()
{
var monkey = Substitute.For<IMonkey>();
var keeper = new ZooKeeper { AssignedMonkey = monkey };
monkey.CurrentFleaCount().Returns(0);

keeper.CleanMonkey();

monkey.Received().CurrentFleaCount();
monkey.DidNotReceive().Clean();
}

In particular, not the way mocks are created, the way a method is stubbed and how the asserts are performed.  The NSubstitute version has less code to create the mock and doesn’t require lambda’s for either the method stub or the asserts making it much more readable.  I’m finding it much nicer to use than Rhino’s syntax and for me less typing and better readability is always a good thing :-)

There’s a lot of other things that the guys have done to make mocking cleaner and I’d strongly recommend you get yourself over to the NSubstitute project site on GitHub, check out the other features and have a play.  There’s still a few rough edges and features to be implemented but the majority of usage scenarios are covered so it’s very much usable for day to day work right now. By the way, Dave Tchepak announces NSubstitute and shows a few more usage examples on his blog, which you should also go and have a look at.

Congratulations to both Dave Tchepak (@davetchepak) and Anthony Egerton (@guywithbeard) for getting this thing together.  Well done, and I hope this project really takes off :-)

Jul 2, 2010

How to Double Click to Diff Pending Changes in TFS

Have you ever looked at a file in the pending changes window and wanted to see what the differences were between that file and the latest version?  If so, then you’ll no doubt have done the right click, sub-menu dance like this:

image

Well, you don’t have to.  There’s actually a few ways to avoid the right clickiness – here’s how:

1. Press Shift + Double Click.

2. Highlight the file and press Shift+Enter

3. Don’t press shift at all! Just change the registry as follows:

Path:     HKCU\Software\Microsoft\VisualStudio\<ver>\TeamFoundation\SourceControl\Behavior
Value:   DoubleClickOnChange (DWORD)

0 == view as the primary command (default)
1== compare as primary command

Setting this registry key will make double-click/enter do a diff instead of viewing the file, and make shift+double-click/enter view the file instead.

 

Enjoy!

I’m a Visual Studio ALM MVP

I was very pleasantly surprised today when I received an email from Microsoft stating that I have been awarded MVP status for my contributions over the last year.

Here’s the proof – my MVP Profile.  Happy days!