Home » Posts tagged "nunit"

Run NUnit from Visual Studio

For the purposes of this post, I’m going to assume that you already have the NUnit Test Runner installed.  The question you are looking to get answered is, “How do I run NUnit from Visual Studio” or even more importantly, “How do I DEBUG NUnit test from Visual Studio”.  The following step by step should help you.

Right click on the project in Solution Explorer that represents your test project. From the resulting menu, select “Properties.” In the resulting window, selec the “Debug” tab from the left-hand side of the window. Continue reading “Run NUnit from Visual Studio”

NUnit Test Code Structure

UnitTestStructure

There are two basic ways to structure the code you will be working on to Unit test the code in your main application using NUnit.  Arrange/Act/Assert (AAA) is what I refer to as the “Classic” method.  It has been around for as long as I’ve known about unit testing. The second method is the Given/When/Then (GWT) structure.

While both methods get the job done and both methods essentially help you structure your test, I think that the Given/When/Then structure helps us think about what we are trying to test from a more functional perspective.  Arrange/Act/Assert is more of a code based approach.

Since, in the end, what we care about is the functionality that we have coded.  I prefer Given/When/Then.  I also think GWT is better suited to Test Driven Development since in Test Driven Development, we are already in the mindset of “What is it that I’m trying to accomplish?”  And not, “What did I do and how do I test it?”

Arrange/Act/Assert

The classic method of arranging our NUnit test code conforms to the “Arrange/Act/Assert” pattern.  Using this pattern, we setup our code so that it is in the state we need it to be to perform the test.  Then we perform some distinct action on the code.  This action should exercise one and only one feature.  And then, finally we assert that the action we performed resulted in some expectation being fulfilled.

What?  Huh?

So, maybe some code will help.

Let’s assume that we have a class, Calculator, that has a method, Add:

public class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }
}

To test this class, we create another class in our test project that we will name CalculatorTest.  Well, what do we want to test in our Calculator class?  We want to test that when we add two numbers together, the proper sum comes back.  So, we’ll need a test method.  It is customary to name our methods what we are trying to test for, so we will call our test method AddShouldReturnSumOfTwoNumbers().

Following the Arrange/Act/Assert pattern, the first part of our method will create the Calculator object, then we will call the Add method, passing it two numbers, and then we will Assert that the proper result was returned.

[TestFixture]
public class CalculatorTest
{
    [Test]
    public void AddShouldReturnSumOfTwoNumbers()
    {
        // Arrange
        var sut = new Calculator();

        // Act
        var returnValue = sut.Add(3, 7);

        // Assert
        Assert.That(returnValue, Is.EqualTo(10));
    }
}

Given/When/Then

An alternate way of thinking about test is by using the Given/When/Then construct.  It essentially arranges the code in the same way, but I think it helps you think about what it is you are trying to test better.  Arrange/Act/Assert (aka AAA) tends to have you think about your code from a programmer’s perspective.  “This is what my code does.”  The Give/When/Then method thinks about the problem more from a requirements perspective.  At the end of the day what is important is that you have test around your code, so I’m not going to spend a lot of time arguing that one way is particularly better than the other.  But GWT is what I use. Since this is my post, that’s what we are going to use for the remainder of this book.

So going back to our Calculator example, what would GWT look like?

[TestFixture]
public class CalculatorTest
{
    [Test]
    public void AddShouldReturnSumOfTwoNumbers()
    {
        // Given that we have a calculator
        var sut = new Calculator();

        // When I add 3 and 7 together
        var returnValue = sut.Add(3, 7);

        // Then the result should be 10
        Assert.That(returnValue, Is.EqualTo(10));
    }
}

See, it’s all the same stuff, so whatever helps you think about what you are testing is what you should use.

NUnit & Visual Studio

Many people starting out with Unit testing get stuck when it comes to using their tools with the Visual Studio environment.  If it isn’t built in, how do we make it work with Visual Studio?  In this article I want to explore the basics of creating a unit test for NUnit and getting it running from Visual Studio.

Basic Structure

To create a unit test, the first thing you will need to do is to create an assembly with a class file to hold the code. The type of assembly you will need to create for your test to be able to run is an assembly of type "Class Library." I’m going to assume that you don’t need the details on how to create that type of project using whatever version of Visual Studio you happen to be using.

Within your new Class Library project, you should find a file named Class1.cs. For the purposes of getting started, you can just leave that file. We’ll talk about how to name your class and test later on. For now, all we want to concentrate on is the basics of what is involved in getting a basic test going and what the components of a test class are that you will repeat over and over again as you create unit test for your applications.

Before we add our first line of code, though, you will want to add references to NUnit in your code. The easiest way to do that is by using NuGet. Since I use Visual Studio 2013, all of the references for how to do things will be using Visual Studio (Premium) 2013. So, if you are using that version, you can just follow along. If not, you may need to do some translating.

From the Visual Studio menu, select "Tools" > "NuGet Package Manager" > "Manage NuGet Packages for Solution…". A window will pop up. Search for NUnit and install the package named "NUnit". There are other packages available that we will discus later on.

Alternatively, you could download NUnit directly from the NUnit site (http://nunit.org) and add a reference directly to nunit.framework.dll.

Code

Now that you have the DLLs installed and referenced in your project, you’ll need to create a test class. For our purposes, we are going to stick with Class1.cs.

There are several things that make a class a test class. First, the class has to be attributed with the [TestFixture] attribute. Second, the methods you want to have run the test have to be attributed with the [Test] attribute and must be public. So, your minimal test class will look something like:

[TestFixture]
public class Class1
{
    [Test]
    public void MyFirstTestMethod()
    {
        // test code here
    }
}

Running Tests

Now that we have a basic test class, go ahead and compile it. We are going to try running the test next. For that we will need a test runner.

There are several ways to run NUnit test. For out purposes, we are going to use the runner that comes with NUnit. But you might also be interested in one of the alternatives. You can get a 30 day trial of ReSharper by JetBrains. ReSharper has many features, but the one I want to talk about here is the test runner. Any test you create will be immediately runnable from within Visual Studio by right clicking on an icon to the left of your code. You are presented with a menu of options including debugging your test. Believe me, this is the easiest way to debug NUnit test that I know of.

Another easy way to run NUnit test from within Visual Studio is by installing the MSTest adapter. You can get this from NuGet.

For the purposes of this article, we are going to use the test runner that comes with NUnit.

So the next thing you’ll need to do is go to NUnit.org and download and install the latest version of NUnit if you didn’t do that already to get the NUnit DLLs installed. I would suggest using the MSI installer rather than the zip file. All we want to be able to do is to run the test.

Once you’ve installed NUnit, there should be a menu option "NUnit" that you can click. This should bring up the GUI runner.

image

Use the "File" -> "Open" to navigate to the "bin" directory of your NUnit test DLL project and open the DLL. You should see a screen that looks something like this:

image

Click the "Run" button to run your test. You should get a green progress bar under the "Run" button and a check box over the icons in the tree on the left indicating that all of the test succeeded.

"Wait?!", you say, "I didn’t test anything, how did they succeed?"

You are right. A test succeeds if it doesn’t fail. Later on this will impact how we structure our test. So keep this in mind.

One of the nice things about the NUnit GUI runner is that you can keep this up while you work on your tests. By default, the system shadow copies the DLL so that you can compile the DLL in your project. When the NUnit GUI runner sees that the file has changed, it will reload it so that it is always running whatever version you recently compiled. You can change this behavior, if you really feel the need to, by navigating to "Tools" -> "Settings…"

Debugging Tests

As with all things related to code, eventually you will need to debug your test. To do this using the the tools that come with NUnit, do the following.

Right click on the project in Solution Explorer that represents your test project. From the resulting menu, select "Properties." In the resulting window, select the "Debug" tab from the left-hand side of the window.

image

You will want to select "Start external program" and point it to the UNnit runner that got installed when you installed NUnit.

Now, whenever you run this project, with or without the debugger, NUnit will start up. Note: there is no reason to pass parameters telling it what DLL you want to run because it will load the last DLL it had up. But, if you wanted to do that, you could pass the location of the DLL as a parameter to the GUI runner. There are other parameters you can us. Check the documentation for the version of NUnit you are using for the specifics.

If you are running .NET 4.x, you’ll want to go to the location in your file system where NUnit.exe lives and find the NUnit.exe.config file. Find the startup element (<startup> …. </startup>) and place this line in between the open and close startup tags:

<supportedRuntime version="4.0" />

If you miss this step, you won’t be able to debug your 4.0 code. Alternatively, you can just set your project to use .NET 3.5.

So, let’s give it a try.

First, put some code in the test method you just created. For our purposes, we’ll just put in a console writeline so we have somplace to put a breakpoint.

public void MyFirstTestMethod()
{
    Console.WriteLine("Inside MyFirstTestMethod");
}

Next set a breakpoint on the Console.WriteLine method and then run your project with the debugger.

Once NUnit loads the DLL, click the "Run" button in NUnit. If everything is setup correctly, you should stop on the breakpoint you set.

Console.WriteLine()

You may have noticed that we put several Console.WriteLines() in our code but they aren’t displaying anywhere. So, where did they go? How can we see them?

By default the "Text Output" tab displays all of the Console.WriteLine() messages as well as all of the test results. If all you care to see is the test results, you should select the "Errors and Failures" tab. Personally, I prefer to work in the "Text Output" tab and I suggest that you do the same.

Not The Only Way

This isn’t the only way to get NUnit & Visual Studio working together.  You could also purchase the ReSharper plugin which has many other features.  But one of the ones I use on a regular basis is the NUnit integration.

You could also use the NUnit test Adapter to make NUnit work with the Visual Studio test engine.  But personally, I don’t like the way the test render using that and I’d much rather use the GUI viewer I’ve discussed in this article.  So, if you want to integrate NUnit & Visual Studio for free, what I’ve outline above is the best way to do it.

NUnit, Unity Dependency Injection, MOQ and Private Fields

loading…

I had an interesting puzzle to solve this week that I thought I would share with you in case someone else is looking for a similar solution.

There was some code that I needed to test that ultimately called into the database. Since this is a UNIT test and all I was interested in testing was one specific function and the state of one specific field in another  object, I had neither the need, nor the desire, to let that call to the database happen.  Since MOQ is  my mocking framework of choice, I wanted to mock out the database object the method was using so that it would return whatever was expected without actually calling down into the database.

There were several problems.  The first was that the database object is a private field in the class I was testing and it got created by the constructor.  Second, the code that needed to use the database object is passing the object by reference (using the “ref” keyword) so that I could no setup my class that needed that object to just ignore it.

There were some other items I needed to inject, but they were pretty straight forward.

Disclaimer

But first, I realize that some purist out there is going to leave me a comment that says you shouldn’t use a Dependency Injection container in your unit test.  My answer to that is, yes, ideally, one should not do this.  But, not everything is ideal.  Not every project is a “green field” project (and in fact about 95% of them aren’t).  And in some cases there is so much technical debt involved that the best we can do is a hack.  Read, Working Effectively with Legacy Code for other illustrations of “hacks” to get code under test.

So, there’s the problem.  It may not make a lot of sense yet, especially if you are not familiar with the tools.  So let’s walk through some code.

The Code

The main method I wanted to test was hanging off a POCO class.  It is using what we call a “visitor” pattern (though I’m pretty sure this is not what the pattern is supposed to look like).  So we have an Accept() method hanging off of it that knows how to store the poco into the database.

That method has a method it calls that hangs off a crud object called Create() that takes the POCO and a reference to the database.

I want to mock the Create() method so that it never actually gets called.  The method should return the POCO as part of a list of the POCO’s type.

Mocking out the crud object is pretty straight forward:

_mockCrud = new Mock<ICrud>()

 

and then registering it with the Unity DI container:

container.RegisterInstance(_mockCrud);

The real issue, and the main point of this post, is that when I wanted to call Create() what I needed to do was:

_mockCrud.Setup(
    x => x.Create(It.IsAny<IPOCOType>(), 
        ref It.IsAny<IDatabaseType>())
    .Returns(pocoList);

Which you can’t do.

What you have to do instead is:

_mockCrud.Setup(
    x => x.Create(It.IsAny<IPOCOType>(),
        ref _database))
    .Returns(pocoList);

And the only way this will work is if the _database variable is pointing to the same object that will ultimately get called.

So, here is the magic that I used to make all that work.

Reflection.

The database object I needed was created as part of the constructor in yet another object that I pass into the Accept() method.  So, I create that object and then use reflection to get the instance of the database from it.

var visitor = new DataVisitor();
var fieldInfo = visitor.GetType()
    .GetField("_database",
        BindingFlags.NonPublic | BindingFlags.Instance);
if(fieldInfo != null)
{
    _database = (Database)fieldInfo.GetValue(visitor);
}

And now I can use the Setup code I’ve already specified.

Hope that helps someone else.