Tag Archives: unit testing

Create and Populate Objects in SpecFlow Scenarios

SpecFlow is definitely my favorite new tool for 2012. If you haven’t checked it out yet, you should. If you’ve checked it out and still don’t get it, come talk to me. I love writing scenarios using business language to help guide my test-driven development. The integration-level tests are proving to be an awesome supplement to more traditional isolated unit tests.

Sometimes it’s hard to come up with a good scenario step because you need to specify several details. Don’t worry, though–SpecFlow’s got ya covered with its Assist Helpers. Let’s say I’m working on some code that has a configuration object that contains my application’s settings. When I’m writing a feature scenario, I might want to provide these settings. I can do just that by putting the details into a table in my scenario.

Configuration.cs

public class Configuration
{
    public string OutputDir { get; set; }
    public bool Enabled { get; set; }
}

Feature1.feature

Scenario: CreateInstance demo
    Given I have the following configuration
        | output dir | enabled |
        | c:\blah    | true    |
    When I do something
    Then what I expected to happen happened

In my step definition, I can import the TechTalk.SpecFlow.Assist namespace to use Assist Helpers like the CreateInstance<T> extension method. When called on a table, CreateInstance will match columns to properties to create and populate an object. Here’s how I use it with the above example:

[Given(@"I have the following configuration")]
public void GivenIHaveTheFollowingConfiguration(Table table)
{
    var config = table.CreateInstance();
}

When creating the object, case-sensitivity and whitespace are ignored, allowing you to create a human-friendly table of your object’s property values. You can also use a vertical table with properties listed as rows. This table will produce the same result as above:

Scenario: CreateInstance demo
    Given I have the following configuration
        | Field      | Value   |
        | output dir | c:\blah |
        | enabled    | true    |
    When I do something
    Then what I expected to happen happened

This technique allows you to create complex objects without having to write any code. You can create highly re-usable steps that rely on the scenario author to provide necessary details in the scenario itself. Simply awesome!

Advertisements

Stubs in Microsoft Fakes

A few weeks back, I wrote an article about using shims in Microsoft Fakes. In addition to shims, Microsoft Fakes also has support for stubs. Stubs in Microsoft Fakes works a lot like other mocking frameworks such as Rhino Mocks, and it comes with a lot of the same limitations (must be visible, must be virtual, etc.). Let’s look at an example of what we can do using stubs in Microsoft Fakes. (Note: Microsoft Fakes requires Visual Studio 2012.)

Before we can use Microsoft Fakes, we need to do a little setup. Here are the steps that need to be performed:

  1. Create a new solution/project; I’m using a C# Console Application named “FakesSample”
  2. Add a new Unit Test Project to the solution; mine is named “FakesSample.Tests”
  3. Add a reference to the project to be tested in the test project
  4. In Solution Explorer, right-click the newly created reference and choose Add Fakes Assembly

And we’ll need some code to test. This is what I’ll be using:

namespace adamprescott.net.FakesSample
{
    using System;

    public class Mammal
    {
        public string Name { get; set; }
    }

    public interface IDataAccess
    {
        Mammal Get(int id);
    }

    public class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();
            p.Run();
        }

        public IDataAccess DataAccess { get; set; }

        public void Run()
        {
            var m = DataAccess.Get(1);
            Console.WriteLine(m.Name);
        }
    }
}

Create a stub

The core functionality of a stub in unit tests is to remove external dependencies and/or provide makeshift functionality. In our code above, there is an IDataAccess that’s used to retrieve Mammal objects by ID. The Microsoft Fakes stub is perfect for this. In code, we create a Mammal object to be returned, and we return it using a lambda in our stub:

var m = new Mammal { Name = "Terry" };
var stubDataAccess = new StubIDataAccess
{
    GetInt32 = x => m
};

Verify a call

The stub gives us our desired behavior, but how do we know the stub was used? We can add verification by setting a flag in our stub implementation and asserting the value after the test is executed.

var m = new Mammal { Name = "Terry" };
var wasCalled = false;
var stubDataAccess = new StubIDataAccess
{
    GetInt32 = x => {
        wasCalled = true;
        return m;
    }
};
// ...
Assert.IsTrue(wasCalled);

I like that Microsoft Fakes makes this capability available without the need of a third party, but I’ll probably be sticking with Rhino Mocks for the time being. I haven’t found anything that I couldn’t do in MS Fakes that I could do with Rhino Mocks, but it often takes a lot more code. Maybe it’s because I’m less familiar with Fakes, or maybe it’s because Rhino Mocks is a more mature mocking framework–I’m not sure.

Here’s the complete unit test example:

namespace adamprescott.net.FakesSample.Tests
{
    using adamprescott.net.FakesSample.Fakes;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class ProgramTest
    {
        [TestMethod]
        public void RunWritesNameToConsole()
        {
            // Arrange
            var target = new Program();

            var m = new Mammal { Name = "Terry" };
            var wasCalled = false;
            var stubDataAccess = new StubIDataAccess
            {
                GetInt32 = x =>
                {
                    wasCalled = true;
                    return m;
                }
            };
            target.DataAccess = stubDataAccess;

            // Act
            target.Run();

            // Assert
            Assert.IsTrue(wasCalled);
        }
    }
}

Test-first Development Cartoons

Lately, I’ve gotten into the habit of keeping a ton of can’t-forget-to-read-this articles open in separate tabs in my browser. It’s gotten to the point where I have so many tabs open that I can’t remember why or how I got to the tab in the first place. It’s kinda fun, though. Going back through the tabs feels like browsing new content that’s all be hand-picked by me for me. Thanks, me of the past!

I was flipping through some of the older tabs and found this Microsoft Patterns & Practices article about unit testing. This article is a bit long, but it serves as a good introduction to unit testing, touching on a variety of topics related to unit tests and automated system testing. There were a couple of cartoons about test-first development that I really liked in this article.

Writing unit tests before you write the code—test-first development—is recommended by most developers who have seriously tried it. Writing the tests for a method or interface makes you think through exactly what you want it to do. It also helps you discuss with your colleagues what is required of this particular unit. Think of it as discussing samples of how your code will be used.

For example, Mort, a developer at Fabrikam, has taken on the task of writing a method deep in the implementation of an ice-cream vending website. This method is a utility, likely to be called from several other parts of the application. Julia and Lars will be writing some of those other components. They don’t care very much how Mort’s method works, so long as it produces the right results in a reasonable time.

In the comic, Mort has been given some requirements and is left to come up with implementation details on his own. He writes tests to show an example of how his method will be used as well as to build in some assumptions. The point of test-first development is that you come up with a way to test before you begin coding. In practice, this is easier said than done, but it’s a good habit to get into. Writing tests first ensures that you write good, testable code. When you write the solution first, it’s much easier to end up with poorly tested or untested (gasp!) code.

The second comic introduces a new piece of functionality. Note that no code had been written at this point, but a new test is added to verify a different behavior of the same code. At the end of the comic, Mort points out that all that’s left to do now that the tests are in place is to write some code that makes the tests pass. Time is spent writing tests and thinking through requirements and scenarios up-front. Then, when you move on to the “real” development, it’s much easier because you’re just writing code to make the tests pass. (Way better than running code and repeating manual tests over and over again!)

ScenarioContext in SpecFlow

I’ve been using SpecFlow pretty regularly for a few weeks now, and I must say, I’m a fan. I find that it’s a lot easier to do test-first development because I’m writing the test in human-readable, business language.

One of the ideas that I didn’t understand right away was how to re-use generated step definitions across features and scenarios. ScenarioContext and FeatureContext give you great options to handle this, though. Let’s check out an example using a modified version of the default scenario SpecFlow generates with a new feature file:

Scenario: Add two numbers
	Given I enter 50 into the calculator
	And I press plus
	And I enter 70 into the calculator
	When I press enter
	Then the result should be 120 be displayed

When I generate step definitions, I might end up with a class that looks like this:

namespace adamprescott.net.Calculator.SpecFlow
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using TechTalk.SpecFlow;

    [Binding]
    public class Calculator_AddSteps
    {
        Calculator calculator = new Calculator();

        [Given(@"I enter (.*) into the calculator")]
        public void GivenIEnterIntoTheCalculator(int p0)
        {
            calculator.Number(p0);
        }

        [Given(@"I press plus")]
        public void GivenIPressPlus()
        {
            calculator.Plus();
        }

        [When(@"I press enter")]
        public void WhenIPressEnter()
        {
            calculator.Enter();
        }

        [Then(@"the result should be (.*) be displayed")]
        public void ThenTheResultShouldBeBeDisplayed(int p0)
        {
            Assert.AreEqual(Convert.ToString(p0), calculator.Display);
        }
    }
}

Okay, not bad. A logical next feature might be subtraction. Some of the steps, like entering numbers and pressing enter, are shared. It would be nice if we could re-use those, but they’re configured to manipulate private variables in the Calculator_AddSteps class. So let’s do some refactoring! Instead of using a member-level variable, I can store my Calculator object in the ScenarioContext, making it accessible to other steps being executed in the same scenario.

// store to ScenarioContext like this:
ScenarioContext.Current.Set<Calculator>(new Calculator());
ScenarioContext.Current.Set<Calculator>(new Calculator(), "Calc");
ScenarioContext.Current["Calc"] = new Calculator();

// retrieve from ScenarioContext like this:
var c = ScenarioContext.Current.Get<Calculator>();
var c = ScenarioContext.Current.Get<Calculator>("Calc");
var c = ScenarioContext.Current["Calc"] as Calculator;

This is overkill for such a simple example, but I separated my shared steps into a new step definitions file. The final solution has three classes for the step definitions: Calculator_AddSteps, Calculator_SubtractSteps, and Calculator_SharedSteps.

Here’s the final solution, broken up by file:

Calculator_Add.feature

Feature: Calculator_Add
	In order to avoid silly mistakes
	As a math idiot
	I want to be told the sum of two numbers

Background:
	Given I have a calculator

Scenario: Add two numbers
	Given I enter 50 into the calculator
	And I press plus
	And I enter 70 into the calculator
	When I press enter
	Then the result should be 120 be displayed

Calculator_AddSteps.cs

namespace adamprescott.net.Calculator.SpecFlow
{
    using TechTalk.SpecFlow;

    [Binding]
    public class Calculator_AddSteps
    {
        [Given(@"I press plus")]
        public void GivenIPressPlus()
        {
            ScenarioContext.Current.Get<Calculator>().Plus();
        }
    }
}

Calculator_SharedSteps.cs

namespace adamprescott.net.Calculator.SpecFlow
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using System;
    using TechTalk.SpecFlow;

    [Binding]
    public class Calculator_SharedSteps
    {
        [Given(@"I have a calculator")]
        public void GivenIHaveACalculator()
        {
            ScenarioContext.Current.Set<Calculator>(new Calculator());
        }

        [Given(@"I enter (.*) into the calculator")]
        public void GivenIEnterIntoTheCalculator(int p0)
        {
            ScenarioContext.Current.Get<Calculator>().Number(p0);
        }

        [When(@"I press enter")]
        public void WhenIPressEnter()
        {
            ScenarioContext.Current.Get<Calculator>().Enter();
        }

        [Then(@"the result should be (.*) be displayed")]
        public void ThenTheResultShouldBeBeDisplayed(int p0)
        {
            Assert.AreEqual(Convert.ToString(p0), ScenarioContext.Current.Get<Calculator>().Display);
        }
    }
}

Calculator_Subtract.feature

Feature: Calculator_Subtract
	In order to avoid silly mistakes
	As a math idiot
	I want to be told the difference between two numbers

Background:
	Given I have a calculator

Scenario: Subtract two numbers
	Given I enter 70 into the calculator
	And I press minus
	And I enter 50 into the calculator
	When I press enter
	Then the result should be 20 be displayed

Calculator_SubtractSteps.cs

namespace adamprescott.net.Calculator.SpecFlow
{
    using TechTalk.SpecFlow;

    [Binding]
    public class Calculator_SubtractSteps
    {
        [Given(@"I press minus")]
        public void GivenIPressMinus()
        {
            ScenarioContext.Current.Get<Calculator>().Minus();
        }
    }
}

Unit Test Private Methods in Abstract Classes

I was sharing what I’d learned about unit testing private methods with some co-workers, and the idea of testing a private method of an abstract class was presented.

PrivateObject deals with this handily by allowing you to specify the type being tested in one of its constructors.

Here’s a simple example. Consider we have an abstract class, Mammal, and a derived class, Human.

public abstract class Mammal
{
    private void SecretMammalStuff()
    {
    }
}

public class Human : Mammal
{
}

We can test Mammal’s private method by doing the following:

var human = new Human();
var po = new PrivateObject(human, new PrivateType(typeof(Mammal)));
po.Invoke("SecretMammalStuff");

If we don’t specify the PrivateType argument in the PrivateObject constructor, we’re not able to access the base class’s private methods. This is the key to testing private methods in an abstract class.

Unit Testing and Private Methods

So you’re a TDD developer.  You code along merrily, writing failing unit tests, implementing them to a point of success, and then you refactor. But then, with no notice–WHAM–a private method. Now what!?

There are different schools of thought for this scenario. One camp says that if it’s not publicly exposed, you shouldn’t be testing it. I think that’s valid, but it’s equally valid to write test code for private methods. Just because a method’s private doesn’t mean it doesn’t deserve the same special attention. And just because I want to test a method that happens to be private doesn’t mean I want to expose it to the rest of the world! Let’s not worry about the debate for now. I’m going to show you how you can override private methods with Microsoft Fakes and how call private methods with Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject.

Override private methods

Problem: You have a private method with behavior that’s disruptive to unit testing. Regardless of the cause of the disruption, you want to provide an alternate implementation.

Solution: Use Microsoft Fakes to shim the private method. (Need to know more about Fakes? Check out my tutorial!)

Here’s how you can do it:

  1. Create an instance of your class
  2. Create a shim from  your class
  3. Override the private method on the shim
  4. Invoke the test method

Here’s a code example:

[TestMethod]
public void SecretMethod_FunctionalityIsOverridden()
{
    using (ShimsContext.Create())
    {
        var target = new FileReader("foo");
        var shim = new ShimFileReader(target);

        bool calledShimMethod = false;
        shim.SecretMethod = () => 
        {
            calledShimMethod = true;
            return "bar";
        };

        target.Read();

        Assert.IsTrue(calledShimMethod);
    }
}

Call private methods

Problem: You want to test a private method, but you can’t because it’s private.

Solution: Use Microsoft Test Framework’s included PrivateObject class.

The only thing I don’t like about PrivateObject is that it (presumably) uses reflection for method names, which means method names will be coded as strings with no compile-time checks. It’s very easy to use, though, and if you need to invoke a private method, I haven’t seen a better way to do it!

Here are the steps:

  1. Create an instance of your class
  2. Create a PrivateObject from your class
  3. Use the PrivateObject‘s Invoke method

And here’s the code:

[TestMethod]
public void SecretMethod_ReturnsHumorousMessage()
{
    var target = new FileReader("foo");
    var privateObject = new PrivateObject(target);
    var actual = privateObject.Invoke("SecretMethod");

    Assert.IsNotNull(actual);
}

Putting it all together (useless, but fun!)

I was able to verify both of these capabilities by writing a single unit test that overrides the private method, then calls the private method. Check it out:

[TestMethod]
public void SecretMethod_FunctionalityIsOverridden()
{
    using (ShimsContext.Create())
    {
        var target = new FileReader("foo");
        var shim = new ShimFileReader(target);

        // override the private method
        bool calledShimMethod = false;
        shim.SecretMethod = () => 
        {
            calledShimMethod = true;
            return "bar";
        };

        // call the private method
        var privateObject = new PrivateObject(target);
        var actual = privateObject.Invoke("SecretMethod");

        // assert that calling the private method
        // used the overridden implementation
        Assert.IsTrue(calledShimMethod);
    }
}

Files as Embedded Resources in Unit Tests

One of the most common unit test mistakes that I see is using relative file paths to actual files. The problem with this is that tests run automatically as part of a build might not have the same file structure that your relative paths assume. A better solution is to use the DeploymentItem attribute in your tests to ensure the necessary resources are copied to the relevant unit test directory, but I prefer a different solution: compiling the files as embedded resources.

A file is added to the project as an embedded resource simply by changing its Build Action in Properties. Once it’s an embedded resource, it can be accessed from your unit tests like this:

private string GetFileContents(string sampleFile)
{
    var asm = Assembly.GetExecutingAssembly();
    var resource = string.Format("MyProject.Tests.SampleFiles.{0}", sampleFile);
    using (var stream = asm.GetManifestResourceStream(resource))
    {
        if (stream != null)
        {
            var reader = new StreamReader(stream);
            return reader.ReadToEnd();
        }
    }
    return string.Empty;
}

Note that the resource name is the Solution Explorer path to the file. So the above example is from a test project named “MyProject.Tests” in a folder named “SampleFiles.” This function accepts a file name and will return the contents of the specified file from that directory as a string.

This technique can be used in conjunction with mocks to simulate a multitude of scenarios like reading a file, retrieving data from a web service, or querying a database.

Here’s a quick example that demonstrates how this could be used to simulate retrieval of data from a web service:

public interface IDataAccess
{
	string GetXmlDataFromWebService();
}

public class MyClass
{
	private readonly IDataAccess _dataAccess;
	
	public MyClass(IDataAccess dataAccess)
	{
		_dataAccess = dataAccess;
	}
	
	public void Execute()
	{
		var xml = _dataAccess.GetXmlDataFromWebService();
		// do more...
	}
}

[TestMethod]
public void Execute_ProcessesXml()
{
	// Arrange
	var mockDataAccess = MockRepository.GenerateMock<IDataAccess>();
	var target = new MyClass(mockDataAccess);
	
	var xml = GetFileContents("TestData.xml");
	mockDataAccess.Expect(x => x.GetXmlDataFromWebService())
		.Return(xml);
	
	// Act
	target.Execute();
	
	// Assert
	mockDataAccess.VerifyAllExpectations();
	// more assertions...
}

Unit Tests: Why I Love ‘Em

Image borrowed from here

Unit tests are one of my favorite things to write as a developer. I simply love them. It’s like a little game I get to play with myself to ensure I’ve covered all possible scenarios and verify that my code is absolutely bulletproof. If I’m doing maintenance work on a project without tests, you better believe it won’t be without tests by the time I’m finished. And when I review another developer’s code and find issues that I know would’ve been caught by even the simplest of unit tests, I feel sad.

There’s been a lot of buzz about unit tests for several years now, but it’s still a challenge getting everybody to buy in. Where’s the real benefit with these tests? Isn’t it going to take me a lot longer if I have to write tests for everything? Aren’t I just making more work for myself when I make the changes that I’ll inevitably be making? No, no, NO!

The benefits of unit tests and test-driven development are so great and so many that whether or not to do it shouldn’t even be a discussion. That said, I realize there’s a path to enlightenment that takes time to travel, and I want to help you get there. So let’s explore some of these endless benefits that I’m speak of…

SOLID Design

Code that is difficult to test is often a result of poor design. If you follow the SOLID design principles, you will find that your code generally lends itself well to unit tests. Writing tests first can help identify a bad design before it’s too late. SOLID principles make testing easier. So, by embracing unit tests and test-driven development, your coding practices will naturally evolve to follow these principles.

  • Single responsibility principle – Testing and verifying an object with a single, clear, defined purpose will be easier than testing a class with multiple, vague responsibilities. Know your class’s purpose, and you’ll have a better idea what tests to write. It’s important to apply this principle to methods, as well. A method that does one thing is easy to test. A method that does 100 things, not so much.
  • Open/closed principle – Making classes extensible will make them flexible in unit test scenarios. One of my favorite techniques is using partial mocks with RhinoMocks, which rely heavily on this principle.
  • Liskov substitution principle – Embracing this principle will help you keep base classes and interfaces simple. This will make consumers of your objects easier to test because less time can be spent repeating unnecessary mocking. Don’t make an IMyDataProvider that has implementation-specific public methods (e.g., CreateDatabaseConnection(), ExecuteStoredProcedure(), etc.). Instead, create a method that does what’s needed, like GetData(). The result is that a MockMyDataProvider can be provided, and you need only mock the GetData method every time instead of each implementation-specific method. Still write tests for those implementation-specific methods, but write them in the tests for your data provider implementation!
  • Interface segregation principle – Interfaces are, in my opinion, the single most important aspect of unit testing layer interactions. Mock objects built from interfaces are absolutely essential for testing most non-trivial scenarios.
  • Dependency inversion principle – Creating mocks, stubs, and fakes is meaningless without a way to inject them into the object being tested. Use constructor injection, property injection, or a dependency injection framework like Unity to provide your object with mocks to remove outside dependencies and test specific functionality.

Fewer Surprises

There is nothing more frustrating than spending hours upon hours troubleshooting an issue only to arrive at a piece of code that has clearly never been run. Write tests, and check your code coverage. If there are lines of code that haven’t been covered, you can evaluate them to determine whether or not additional tests should be written. Play the what-else-could-possibly-go-wrong-here game with yourself. Enforce your own assumptions with exceptions, and test those. If you expect an argument to be not-null, write a test that expects an ArgumentNullException to be thrown; that will be significantly easier to troubleshoot than a null reference exception.

Improved Maintainability

If you’ve spent any significant time maintaining the work of others, you know this is a big one. It’s unsettling to find yourself in the middle of someone else’s 1000-line function with a block of commented code that looks like it does exactly what’s been reported to not be happening. Clearly, removing it was an intentional move, but what will you be breaking by uncommenting it? If a test is written (MammothMethod_ShouldNotCallDatabaseDirectly()), and you uncomment the code that calls the database directly causing that test to fail, you’ll have received two yellow flags warning you that maybe this is a bad approach. Without the test, a developer shrugs, uncomments the code, feels good about it, and re-introduces a bug that was likely fixed previously by another developer. (Didn’t we fix that two releases ago?) Writing tests for your fixes ensures that you aren’t on the other end of that scenario where somebody undoes your fixes. (If they still undo your fix and break or refactor your test in the process, be sure to yell at them.)

Unit tests are also helpful in terms of code management when complex branching strategies are employed. Let’s say you have 20 developers working in different branches. When the branches are brought back together, how can you confirm that changes were not lost? With unit tests in place, you simply need to run the tests. Since that should be happening automatically with each build anyway, all you need to do is verify that the test are there. This really beats the alternative of reviewing code to see if a particular change is included. Plus you feel good as a code-mover knowing that the code is verifying itself with each move.

Well-Tested, High Quality Solutions

At the end of the day, what you’re really trying to produce is a quality solution. You want your deliverables to work correctly when your assumptions are met and handle unexpected scenarios gracefully. You want to tell your users how your application will handle any situation they can come up with. You want your users to feel great about you, whether it’s your company, your product, or you specifically. Unit tests can help you do all this. What happens if the web service isn’t available? There’s a unit test to verify an email is sent. How can I audit queries to the database? There’s a unit test to verify logging. What if an expected record is missing? There’s a test for that, too. If you can think of it, make sure you’ve tested it. Write the tests as you go, and you’ll be sure not to affect features implemented earlier. At the end of development, your code will have a collection of tests self-verifying every feature and enforcing all assumptions.

Did it take more code? Yes.
Did it take more time? Arguably.
Will the final product have higher quality, require less maintenance, and result in a net decrease in total development effort over time? Definitely.

Verify Function Arguments Using Constraints in Rhino Mocks

Verifying arguments passed into a mocked or stubbed method can help you write more specific, robust unit tests. This is easily accomplished with Rhino Mocks by using Constraints.

As an example, let’s write a test for the function MyClass.MyMethod in the code below:

public interface IMyDependency
{
    void DependencyMethod(MyResult myResult);
}

public class MyResult
{
    public int Code;
}

public class MyClass
{
    public IMyDependency MyDependency { get; set; }

    public MyClass(IMyDependency myDependency)
    {
        MyDependency = myDependency;
    }

    public void MyMethod(string input)
    {
        switch (input)
        {
            case "A":
                MyDependency.DependencyMethod(
                    new MyResult { Code = 1 });
                break;
            case "B":
                MyDependency.DependencyMethod(
                    new MyResult { Code = 2 });
                break;
            default:
                break;
        }
    }
}

The first thing we need to do is create a mock IMyDependency and verify that its DependencyMethod is called, so let’s do that:

[TestMethod]
public void MyMethodTest()
{
    // Arrange
    var mockMyDependency = MockRepository.GenerateMock();
    var target = new MyClass(mockMyDependency);

    mockMyDependency.Expect(
        x => x.DependencyMethod(Arg<MyResult>.Is.Anything));

    const string input = "A";

    // Act
    target.MyMethod(input);

    // Assert
    mockMyDependency.VerifyAllExpectations();
}

This test passes, but how do we know the argument with the correct value was used? We can modify our mock object’s Expect call to use argument constraints to do this!

mockMyDependency.Expect(
    x => x.DependencyMethod(Arg<MyResult>.Matches(arg => arg.Code.Equals(1))));

Now my test only passes when the mock is called with an argument that matches the specified criteria. This is obviously a very basic example, but the fact that you can pass a delegate or derive a custom class from Rhino Mocks’s AbstractConstraint class makes this a very powerful feature.

Convert a Class Library to a Test Project in Visual Studio

Occasionally, you may run into a Visual Studio Class Library project that contains unit tests. This can be a frustrating scenario because creating a unit test using Visual Studio’s right-click context menus will not allow you to add a test to the project.

This can be remedied quite easily, though, by adding the correct project type guid to the Class Library’s project file. Here are the steps to do this from within Visual Studio:

  1. Right-click the project in Solution Explorer and choose Edit Project File
  2. Add a new child in the <PropertyGroup> node:
    <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
  3. Save your changes and close the file
  4. Right-click the project in Solution Explorer and choose Reload Project

After following those steps, your project will show in the list of output projects in the Create Unit Tests dialog box.

For a list of known project type Guids, check out this site: http://www.mztools.com/articles/2008/mz2008017.aspx