Tag Archives: Mock

WireMock.Net

I was recently introduced to the WireMock.Net package. This is a .Net implementation of WireMock.

The basic idea where is that you can mock or stub a HTTP call. For example, you can tell it that when https://localhost:1234/test is called then a specific response should be returned – you could, for example, force it to error.

To get started, install the package:

install-package wiremock.net

This is a hefty package, so make sure it’s restricted to your test project.

The following code will replace the URL above with a response of “aaa”:

using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;

Console.WriteLine("Hello, World!");


var request = Request.Create()    
    .WithPath("/test")
    .UsingGet();

var response = Response.Create()
    .WithStatusCode(200)
    .WithBody("aaa");

WireMockServer wireMockServer = WireMockServer.Start(1234);
wireMockServer
    .Given(request)
    .RespondWith(response);


HttpClient client = new HttpClient();
var result = await client.GetAsync("http://localhost:1234/test");
if (result != null && result.IsSuccessStatusCode)
{
    var output = await result.Content.ReadAsStringAsync();
    Console.WriteLine(output);
}

I did, at first, try to run this for an actual site (e.g. to intercept google.com or something), but it won’t allow that, only localhost (at least, as far as I could see). A friend at work pointed out that, in a test, you would pass the URL in through the config anyway, and so you could change it to localhost.

References

https://pcholko.com/posts/2021-04-05/wiremock-integration-test/

Introduction to Unit Tests (with examples in .Net) – Part 3 – Test Frameworks and Manual Mocks

So far, in this series of posts on the basics of unit tests, we’ve spoken about concepts and methodologies, but we’ve steered away from using any specific frameworks or tools. In this post, we’ll investigate what a test framework can do for us.

We’ll continue to work with the code that we created in the previous post, but we’ll address the issues that we still had at the end of that post.

A Recap of the Story So Far

At the end of the previous post, we had the following code:

for (int i = 1; i <= 100; i++)
{
    // Arrange
    Func<string> mockInput = () => "5";
 
    // Act
    string result = RunMethod(mockInput);
 
    // Assert
    if (result == "Well done, you guessed!")
    {
        Console.WriteLine("Test Passed");
        break;
    }
}
 
for (int i = 1; i <= 100; i++)
{
    // Arrange
    Func<string> mockInput = () => "5";
 
    // Act
    string result = RunMethod(mockInput);
 
    // Assert
    if (result.StartsWith("Sorry, that was the wrong number"))
    {
        Console.WriteLine("Test Passed");
        break;
    }
}
 
{
    // Arrange
    Func<string> mockInput = () => "";
 
    // Act
    string result = RunMethod(mockInput);
 
    // Assert
    if (result == "Invalid guess")
    {
        Console.WriteLine("Test Passed");
    }
}

We had yet to introduce any tools or frameworks, but we had managed to test our code. We still had the following issues, however:

1. The tests passed, but we visually have to visually ascertain that.
2. We were outputting to the console needlessly.
3. Our tests were not resilient – a change of a single character in the user output, and the tests would break.
4. The tests were not deterministic – they were dependent on the result of a pseudo random number.

In this post, we’ll address these issues in order (apart from the third one, but we’ll come back to that) : we’ll start with the first.

1. The tests passed, but we visually have to visually ascertain that

How can we ascertain the result of a test without watching to see what happens with the test. One thing we could do is something similar to the following:

int RunTest1()
{
    for (int i = 1; i <= 100; i++)
    {
        // Arrange
        Func<string> mockInput = () => "5";

        // Act
        string result = RunMethod2(mockInput);

        // Assert
        if (result == "Well done, you guessed!")
        {
            Console.WriteLine("Test Passed");
            return 0;
        }
    }
    return 1;
}

int RunTest2()
{
    for (int i = 1; i <= 100; i++)
    {
        // Arrange
        Func<string> mockInput = () => "5";

        // Act
        string result = RunMethod2(mockInput);

        // Assert
        if (result.StartsWith("Sorry, that was the wrong number"))
        {
            Console.WriteLine("Test Passed");
            return 0;
        }
    }
    return 1;
}

int RunTest3()
{
    // Arrange
    Func<string> mockInput = () => "";

    // Act
    string result = RunMethod2(mockInput);

    // Assert
    if (result == "Invalid guess")
    {
        Console.WriteLine("Test Passed");
        return 0;
    }
    return 1;
}

Console.WriteLine(RunTest1());
Console.WriteLine(RunTest2());
Console.WriteLine(RunTest3());

There’s a lot of code here, but all we’ve actually done is wrap the tests up in functions, and then returned a value based on the result of the test. This means that we can write something like this:

if (RunTest1() != 0 | RunTest2() != 0 | RunTest3() != 0)
{
    Console.WriteLine("Some tests failed");
}

In case you didn’t know, the single pipe (|) in C# in a bitwise or – that is, it will execute all conditions regardless of the result and then evaluate the result, a logical or (||) would only run the tests until one failed and then exit the condition.

This approach also helps with the second issue.

2. We were outputting to the console needlessly

We’re outputting to the console for two reasons: the first is to validate the tests; we can now simply remove all of those from the test, since we have an actual value that we can test against. The second reason is that the code itself outputs to the console. As has been mentioned in a previous post, there are ways to redirect the output of the console without mocking it; however, I’m trying to keep this series generic, and that is specific to the .Net console (although I strongly suspect that most languages provide a similar concept).

To get around this, we could replicate what we did in the second post; however, we can also take a slightly different approach and wrap the entire input / output functionality in its own class; for example:

    internal class ConsoleInputOutputWrapper
    {
        public void Output(string text) => Console.WriteLine(text);
        public string GetInput(string prompt)
        {
            Output(prompt);
            return Console.ReadLine();
        }
    }

This idea gives us some additional benefits – as you can see, we already have the prompt and input in a single method; and we could go further – we could do some validation inside the method, too; what if the user doesn’t enter anything:

        public string GetInput(string prompt)
        {            
            while (true)
            {
                Output(prompt);
                string? answer = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(answer)) return answer;
            }
        }

We can now replace the direct references to Console with references to this:

string RunMethod(Func<string> readData)
{
    var io = new ConsoleInputOutputWrapper();
    int myNumber = Random.Shared.Next(100) + 1;

    io.Output("Guess the number that I'm thinking between 1 - 100");
    string? guess = readData();
    string result = BusinessLogic2(myNumber, guess);
    io.Output(result);
    return result;
}

We haven’t actually changed anything here, though – the console is still being written to. We need to be able to replace the functionality within the system for our test. We can do that by replacing the concrete class with an interface.

Adding an Interface

Adding an interface is much simpler than it may sound. Let’s see what needs to change in our ConsoleInputOutputWrapper class:

internal class ConsoleInputOutputWrapper : IInputOutputWrapper

We’ve implemented an interface that we’ve named IInputOutputWrapper – we’ve named it this because it’s more generic (that is, it doesn’t actually need to be a Console).

The interface just needs to specify the public methods in the class:

    internal interface IInputOutputWrapper
    {
        void Output(string text);
        string GetInput(string prompt);
    }

Whilst this syntax is specific to C#, the concept of an interface is not.

While we’re introducing an interface, and to clean our code a little, we can extract both our RunMethod and BusinessLogic methods into their own class – let’s call it Game:

    internal class Game
    {
        public string RunMethod(Func<string> readData)
        {
            var io = new ConsoleInputOutputWrapper();
            int myNumber = Random.Shared.Next(100) + 1;

            io.Output("Guess the number that I'm thinking between 1 - 100");
            string? guess = readData();
            string result = BusinessLogic(myNumber, guess);
            io.Output(result);
            return result;
        }

        public string BusinessLogic(int myNumber, string guessedNumber)
        {
            if (string.IsNullOrEmpty(guessedNumber))
            {
                return "Invalid guess";
            }

            if (int.Parse(guessedNumber) == myNumber)
            {
                return "Well done, you guessed!";
            }
            else
            {
                return $"Sorry, that was the wrong number, I was thinking of {myNumber}";
            }
        }

    }

This makes things much simpler. We can now create a constructor, and pass in our new interface:

    internal class Game
    {
        private readonly IInputOutputWrapper _inputOutputWrapper;

        public Game(IInputOutputWrapper inputOutputWrapper)
        {
            _inputOutputWrapper = inputOutputWrapper;
        }

Now that we have this instance, we can simply replace the method with a reference to this instead:

        public string RunMethod()
        {            
            int myNumber = Random.Shared.Next(100) + 1;
            
            string guess = _inputOutputWrapper.GetInput("Guess the number that I'm thinking between 1 - 100");
            string result = BusinessLogic(myNumber, guess);
            _inputOutputWrapper.Output(result);
            return result;
        }

We can now update our tests to call this new class, but we can pass in our own version of the IInputOutputWrapper, which may look like this:

    internal class MockInputOutputWrapper : IInputOutputWrapper
    {
        public string GetInput(string prompt)
        {
            return "5";
        }

        public void Output(string text) { }
    }

The test would then look something like this:

    for (int i = 1; i <= 100; i++)
    {
        // Arrange
        var inputOutputWrapper = new MockInputOutputWrapper();
        var sut = new Game(inputOutputWrapper);

        // Act
        string result = sut.RunMethod();

        // Assert
        if (result == "Well done, you guessed!")
        {            
            return 0;
        }
    }
    return 1;

Next, we’ll skip number 3 and jump to 4.

4. The tests were not deterministic – they were dependent on the result of a pseudo random number

We can use the same pattern to create a wrapper for our random number chooser:

    internal class RandomNumberChooser : IRandomNumberChooser
    {
        public int Choose() =>
            Random.Shared.Next(100) + 1;        
    }

We can then mock that out, as before:

internal class MockRandomNumberChooser : IRandomNumberChooser
{
    public int Choose() => 12;
}

This definitely works, but it’s not brilliant. We have a few remaining issues – for example, if we want to test the number are the same, or different, we’ll need two mock classes. There are ways around this, too – for example:

    internal class MockInputOutputWrapper : IInputOutputWrapper
    {
        private readonly string _inputValue;

        public MockInputOutputWrapper(string inputValue) =>
            _inputValue = inputValue;        

        public string GetInput(string prompt) => _inputValue;        

        public void Output(string text) { }
    }

We’ll come back to neater ways to achieve this in a future post, but for now, let’s put all this together and introduce a test framework.

Introducing a Test Framework

Test frameworks give you four basic things (some, in fact most, do more, but these are the absolute basics that you need – otherwise, you might as well roll your own):

1. A return value from the test run to determine whether the tests pass or fail
2. An ability to assert a value is in a given state
3. Some kind of integration into your IDE
4. Method discovery (that is, some way to mark your tests as tests)

For this example, we’ll use xUnit.net. Every language has its own options here – in .Net I’ve used MS Test, Nunit, and xUnit – and they’re all broadly the same; I’ve also seen libraries in Javascript and Python and, again, they mostly do the same stuff.

We’ll need to install the following libraries:

Install-Package Microsoft.Test.Sdk
install-package Xunit
Install-Package Xunit.Runner.Console
Install-Package Xunit.Runner.VisualStudio

This will enable you to create a test such as this:

[Fact]
public void RunMethod_GuessedCorrectly_CorrectTextReturned()
{
    // Arrange
    var inputOutputWrapper = new MockInputOutputWrapper("12");
    var randomNumberChooser = new MockRandomNumberChooser();
    var sut = new Game(inputOutputWrapper, randomNumberChooser);

    // Act
    string result = sut.RunMethod();

    // Assert
    Assert.Equal("Well done, you guessed!", result);
}

We no longer need to run this 100 times, because we can force a correct and incorrect guess:

        [Fact]
        public void RunMethod_GuessedIncorrectly_CorrectTestReturned()
        {
            // Arrange
            var inputOutputWrapper = new MockInputOutputWrapper("13");
            var randomNumberChooser = new MockRandomNumberChooser();
            var sut = new Game(inputOutputWrapper, randomNumberChooser);

            // Act
            string result = sut.RunMethod();

            // Assert
            Assert.StartsWith("Sorry, that was the wrong number", result);
        }

Summary

We’ve now seen how we can manually mock functionality, and how that can help us to accurately test methods; we’ve also introduced a testing framework. In the next post, we’ll discuss mocking frameworks, and how they can make this even easier. We’ll also re-visit the test resilience.

Introduction to Unit Tests (with examples in .Net) – Part 2 – Refactoring and Mocking

This forms the second in a short series of posts on unit tests. You can find the first post in this series here.

In this post, I’ll be expanding the points raised in the first post to cover a slightly more realistic scenario, and offering some tips of how re-factoring might help with the creation of unit tests. We’ll also cover the basic principles behind mocking – I’m intending to cover this in more detail in a future post of this series.

A Quick Recap

You’re welcome (and encouraged) to go back to the first post in the series; however, to summarise, we discussed the Arrange/Act/Assert pattern, and how it can help us structure a unit test; we spoke about the FIRST principles of testing, and thereby the attributes that we should look for in a good unit test.

What we specifically didn’t cover was any testing frameworks, the concept of mocking or any mocking frameworks, or how to write a unit test in a scenario where you’re not simply adding two numbers together.

A More Realistic Unit Test

If we take an example of any level of complexity, we might question some of the points that were made in the first post. After all, very few methods would simply take two numbers and add them together – or, if they do, perhaps we need to reconsider the language that we’re using.

Let’s look at a simple console application:

int myNumber = Random.Shared.Next(100) + 1;

Console.WriteLine("Guess the number that I'm thinking between 1 - 100");
var guess = Console.ReadLine();
if (string.IsNullOrEmpty(guess))
{
    Console.WriteLine("Invalid guess");
    return;
}

if (int.Parse(guess) == myNumber)
{
    Console.WriteLine("Well done, you guessed!");
}
else
{
    Console.WriteLine($"Sorry, that was the wrong number, I was thinking of {myNumber}");
}

If you had to test this code, how would you do it?

In fact, it’s really difficult, because every time you run it, the number is different. This is a simple piece of code, there’s only 3 code paths; arguably, your strategy could be: run it once and enter a blank value, run it once and enter a non-numeric value, run it 100 more times and hope that you’ll get the number right once.

Writing a Test

As before, let’s start with the manual test that we’ve just described; arguably, we could simply automate this. We’d probably do something like this:

        public static void RunTest()
        {
            // Run method here - check that a blank entry works

            // Run method here - check that a numeric entry works

            for (int i = 0 ; i < 100; i++)
            {
                // Run method here - exit this loop once we've determined that we have a correct and incorrect guess

            }
        }

In fact, running that exact test would be possible – we could simply redirect the console input and output; however, for the purposes of this post, we’ll bypass that method (as it is quite specific to writing a .Net Console app), and we’ll re-factor our code a little.

Refactoring

We can refactor it by splitting the method into two; one method that accepts the input, and one that runs the business logic:

void RunMethod()
{
    int myNumber = Random.Shared.Next(100) + 1;

    Console.WriteLine("Guess the number that I'm thinking between 1 - 100");
    var guess = Console.ReadLine();
    BusinessLogic(myNumber, guess);
}

void BusinessLogic(int myNumber, string guessedNumber)
{
    if (string.IsNullOrEmpty(guessedNumber))
    {
        Console.WriteLine("Invalid guess");
        return;
    }

    if (int.Parse(guessedNumber) == myNumber)
    {
        Console.WriteLine("Well done, you guessed!");
    }
    else
    {
        Console.WriteLine($"Sorry, that was the wrong number, I was thinking of {myNumber}");
    }
}

All we’ve done here is split the method into two methods – the code is exactly the same as it was before. However, now we can run the code in our test without worrying about the input:

        public static void RunTest()
        {
            // Check that a blank entry works
            BusinessLogic(3, "");

            // Check that a non-numeric entry works
            BusinessLogic(3, "aardvark");

            for (int i = 1; i <= 100; i++)
            {
                // Check that false and true numbers work
                BusinessLogic(i, "2");
            }
        }

It still feels a lot like we’re only testing half of the code. We aren’t testing the calling method.

Mocking

Let’s refactor a little further. Instead of using the console, we’ll simply create our own method that performs the same task:

private static string? GetInput() => Console.ReadLine();    

Again, no real change here, we’re just wrapping the code that accepts input in a method that we control.

Now that we’ve done this, we can use our own method to accept input, instead of the Console methods. There’s a number of ways we could do this but, perhaps the easiest, is to pass the GetInput method into the RunMethod method as a parameter:

public static void RunMethod(Func<string> readData)
    {

        int myNumber = Random.Shared.Next(100) + 1;

        Console.WriteLine("Guess the number that I'm thinking between 1 - 100");
        string? guess = readData();
. . .

Here, we’re simply changing two things: we’re accepting a delegate into our main method, and then we’re calling that, instead of the Console.ReadLine().

What’s the point of doing that? Well, now that we control that function as a parameter, we can mock the function, and replace it with our own functionality.

In fact, we are not technically discussing a mock here, but a stub. For the purpose of this post, we’ll simply group them together with the working definition that a mock is: “anything that replaces functionality for the purpose of testing”. I intend to re-visit this in a future post and go into more detail on the difference between the two.

Let’s jump to our test.

Arrange

In the test, we can now replace this functionality with a specific value:

        public static void RunTest()
        {
             // Arrange
            Func<string> mockInput = () => "5"; . . .

We’ve now established the input of the method, the next step is to be able to assert that the test worked. In fact, that’s very difficult with the code as it currently is, because we just display output to the user. To finish this post off, we’ll refactor this as little as we can; imagine we take the business logic function and change it to be like this:

string BusinessLogic(int myNumber, string guessedNumber)
{
    if (string.IsNullOrEmpty(guessedNumber))
    {        
        return "Invalid guess";
    }

    if (int.Parse(guessedNumber) == myNumber)
    {
        return "Well done, you guessed!";
    }
    else
    {
        return $"Sorry, that was the wrong number, I was thinking of {myNumber}";
    }
}

All we’ve changed here is that we’re returning the string, instead of outputting it. We can then change the calling method to do the output:

string RunMethod(Func<string> readData)
{
    int myNumber = Random.Shared.Next(100) + 1;

    Console.WriteLine("Guess the number that I'm thinking between 1 - 100");
    string? guess = readData();
    string result = BusinessLogic(myNumber, guess);
    Console.WriteLine(result);
    return result;
}

Same idea again, a very small change of writing the output, and returning the result again. The functionality hasn’t changed, but now we have something to test against.

Assert

We can now write out test method to look something like this:

for (int i = 1; i <= 100; i++)
{
    // Arrange
    Func<string> mockInput = () => "5";

    // Act
    string result = RunMethod(mockInput);

    // Assert
    if (result == "Well done, you guessed!")
    {
        Console.WriteLine("Test Passed");
        break;
    }
}

for (int i = 1; i <= 100; i++)
{
    // Arrange
    Func<string> mockInput = () => "5";

    // Act
    string result = RunMethod(mockInput);

    // Assert
    if (result.StartsWith("Sorry, that was the wrong number"))
    {
        Console.WriteLine("Test Passed");
        break;
    }
}

{
    // Arrange
    Func<string> mockInput = () => "";

    // Act
    string result = RunMethod(mockInput);

    // Assert
    if (result == "Invalid guess")
    {
        Console.WriteLine("Test Passed");
    }
}

There’s three distinct tests here and, unless unlucky, they’ll all pass. There’s definitely some work left to do here, as we still have the following problems:

1. Although the tests can pass, we have to visually ascertain that.
2. We’re outputting to the console needlessly.
3. Our tests are not resilient – if I change a single character in the user output, the tests will break.
4. The tests are not deterministic – they are dependent on the result of a pseudo random number.

In the next post, we’ll address these issues: we’ll introduce a test framework, and further refactor this code such that we can be confident that cosmetic changes will not break the tests.

Mocking IConfiguration Extension Method

In this post I wrote about the use of app settings in Asp.Net Core. One thing that I didn’t cover at the time was the fact that, as an extension library, the configuration extensions weren’t very easy to include in unit tests. Of course the intention is that you read the configuration at the start, pass through a model class and no mocking is required.

However, sometimes you’ll find yourself wanting to mock out a particular setting. Before I get into this, this post is heavily based on this article which describes the same process.

The following is a code sample using Moq:

            var configuration = new Mock<IConfiguration>();

            var configurationSection = new Mock<IConfigurationSection>();
            configurationSection.Setup(a => a.Value).Returns("testvalue");

            configuration.Setup(a => a.GetSection("TestValueKey")).Returns(configurationSection.Object);            

This will cause any call to get the app settings key “TestValueKey” to return “testvalue”. As is stated in the linked article, whilst GetValue is an extension method, GetSection is not, but is (internally) called by GetValue.

References

https://dejanstojanovic.net/aspnet/2018/november/mocking-iconfiguration-getvalue-extension-methods-in-unit-test/

Using NSubstitute for partial mocks

I have previously written about how to, effectively, subclass using Nsubstitute; in this post, I’ll cover how to partially mock out that class.

Before I get into the solution; what follows is a workaround to allow badly written, or legacy code to be tested without refactoring. If you’re reading this and thinking you need this solution then my suggestion would be to refactor and use some form of dependency injection. However, for various reasons, that’s not always possible (hence this post).

Here’s our class to test:

public class MyFunkyClass
{
    public virtual void MethodOne()
    {        
        throw new Exception("I do some direct DB access");
    }
 
    public virtual int MethodTwo()
    {
        throw new Exception("I do some direct DB access and return a number");

        return new Random().Next(5);
    }
 
    public virtual int MethodThree()
    {
        MethodOne();
        if (MethodTwo() <= 3)
        {
            return 1;
        }
 
        return 2;
    }
}

The problem

Okay, so let’s write our first test:

[Fact]
public void Test1()
{
    // Arrange
    MyFunkyClass myFunkyClass = new MyFunkyClass();
 
    // Act
    int result = myFunkyClass.MethodThree();
 
    // Assert
    Assert.Equal(2, result);
}

So, what’s wrong with that?

Well, we have some (simulated) DB access, so the code will error.

Not the but a solution

The first thing to do here is to mock out MethodOne(), as it has (pseudo) DB access:

[Fact]
public void Test1()
{
    // Arrange
    MyFunkyClass myFunkyClass = Substitute.ForPartsOf<MyFunkyClass>();
    myFunkyClass.When(a => a.MethodOne()).DoNotCallBase();
 
    // Act
    int result = myFunkyClass.MethodThree();
 
    // Assert
    Assert.Equal(2, result);
}

Running this test now will fail with:

Message: System.Exception : I do some direct DB access and return a number

We’re past the first hurdle. We can presumably do the same thing for MethodTwo:

[Fact]
public void Test1()
{
    // Arrange
    MyFunkyClass myFunkyClass = Substitute.ForPartsOf<MyFunkyClass>();
    myFunkyClass.When(a => a.MethodOne()).DoNotCallBase();
    myFunkyClass.When(a => a.MethodTwo()).DoNotCallBase();
 
    // Act
    int result = myFunkyClass.MethodThree();
 
    // Assert
    Assert.Equal(2, result);
}

Now when we run the code, the test still fails, but it no longer accesses the DB:

Message: Assert.Equal() Failure
Expected: 2
Actual: 1

The problem here is that, even though we don’t want MethodTwo to execute, we do want it to return a predefined result. Once we’ve told it not to call the base method, you can then tell it to return whatever we choose (there are separate events – see the bottom of this post for a more detailed explanation of why); for example:

[Fact]
public void Test1()
{
    // Arrange
    MyFunkyClass myFunkyClass = Substitute.ForPartsOf<MyFunkyClass>();
    myFunkyClass.When(a => a.MethodOne()).DoNotCallBase();
    myFunkyClass.When(a => a.MethodTwo()).DoNotCallBase();
    myFunkyClass.MethodTwo().Returns(5);
 
    // Act
    int result = myFunkyClass.MethodThree();
 
    // Assert
    Assert.Equal(2, result);
}

And now the test passes.

TLDR – What is this actually doing?

To understand this better; we could do this entire process manually. Only when you’ve felt the pain of a manual mock, can you really see what mocking frameworks such as NSubtitute are doing for us.

Let’s assume that we don’t have a mocking framework at all, but that we still want to test MethodThree() above. One approach that we could take is to subclass MyFunkyClass, and then test that subclass:

Here’s what that might look like:

class MyFunkyClassTest : MyFunkyClass
{
    public override void MethodOne()
    {
        //base.MethodOne();
    }
 
    public override int MethodTwo()
    {
        //return base.MethodTwo();
        return 5;
    }
}

As you can see, now that we’ve subclassed MyFunkyClass, we can override the behaviour of the relevant virtual methods.

In the case of MethodOne, we’ve effectively issued a DoNotCallBase(), (by not calling base!).

For MethodTwo, we’ve issued a DoNotCallBase, and then a Returns statement.

Let’s add a new test to use this new, manual method:

[Fact]
public void Test2()
{
    // Arrange 
    MyFunkyClassTest myFunkyClassTest = new MyFunkyClassTest();
 
    // Act
    int result = myFunkyClassTest.MethodThree();
 
    // Assert
    Assert.Equal(2, result);
}

That’s much cleaner – why not always use manual mocks?

It is much cleaner if you always want MethodThree to return 5. Once you need it to return 2 then you have two choices, either you create a new mock class, or you start putting logic into your mock. The latter, if done wrongly can end up with code that is unreadable and difficult to maintain; and if done correctly will end up in a mini version of NSubstitute.

Finally, however well you write the mocks, as soon as you have more than one for a single class then every change to the class (for example, changing a method’s parameters or return type) results in a change to more than one test class.

It’s also worth mentioning again that this problem is one that has already been solved, cleanly, by dependency injection.

Short Walks – NSubstitute – Subclassing and Partial Substitutions

I’ve had this issue a few times recently. Each time I have it, after I’ve worked out what it was, it makes sense, but I keep running into it. The resulting frustration is this post – that way, it’ll come up the next time I search for it on t’internet.

The Error

The error is as follows:

“NSubstitute.Exceptions.CouldNotSetReturnDueToNoLastCallException: ‘Could not find a call to return from.”

Typically, it seems to occur in one of two circumstances: substituting a concrete class and partially substituting a concrete class; that is:

var myMock = Substitute.ForPartsOf<MyClass>();

Or:

var myMock = Substitute.For<MyClass>();

Why?

If you were to manually mock out an interface, how would you do that? Well, say you had IMyClass, you’d just do something like this:

public class MyClassMock : IMyClass 
{
	// New and imaginative behaviour goes here
}

All’s good – you get a brand new implementation of the interface, and you can do anything with it. But what would you do if you were trying to unit test a method inside MyClass that called another method inside MyClass; for example:

public class MyClass : IMyClass
{
	public bool Method1()
{
		int rowCount = ReadNumberOfRowsInFileOnDisk();
		Return rowCount > 10;
	}
	
	public int ReadNumberOfRowsInFileOnDisk()
	{
		// Opens a file, reads it, and returns the number of rows
	}
}

(Let’s not get bogged down in how realistic this scenario is, or whether or not this is good practice – it illustrates a point)

If you want to unit test Method1(), but don’t want to actually read a file from the disk, you’ll want to replace ReadNumberOfRowsInFileOnDisk(). The only real way that you can do this is to subclass the class; for example:

public class MyClassMock : MyClass

You can now test the behaviour on MyClass, via MyClassMock; however, you still can’t* override the method ReadNumberOfRowsInFileOnDisk() because it isn’t virtual. If you make the method virtual, you can override it in the subclass.

The same is true with NSubstitute – if you want to partially mock a class in this way, it follows the same rules as you must if you would to roll your own.

Footnotes

* There may, or may not be one or two ways to get around this restriction, but let’s at least agree that they are, at best, unpleasant.

Mocking IPrinciple.Identity and Claims in NSubstitute

In ASP.Net, there is a concept of an identity. Built on top of this is an authentication system based on claims; allowing applications to implement a claims based authentication system. That is, I can determine if my user has “Administrator” privileges in the following syntax:

var claim = ClaimsIdentity.FindFirstValue("Administrator");

For more information about how claims work, see this excellent explanation. This post is not really concerned with how claims work, but rather, how to mock them out; which is much more difficult than you might guess.

In the references below, you’ll see a number of different strategies to mock out the claims and principle objects. There also seems to be a loose consensus that even attempting to do this is folly. However, I’ve cobbled together a set of mocks using NSubstitute that work. I’m not claiming that they work in all cases, or that they will work in any situation other than the specific one that I am trying to solve; but it did work for that, and so I thought it useful enough to share.

var myController = new MyController();
 
var mockClaim = new Claim("Administrator", "test");
 
var identity = Substitute.For<ClaimsIdentity>();
identity.Name.Returns("test");
identity.IsAuthenticated.Returns(true);
identity.FindFirst(Arg.Any<string>()).Returns(mockClaim);
 
var claimsPrincipal = Substitute.For<ClaimsPrincipal>();
claimsPrincipal.HasClaim(Arg.Any<string>(), Arg.Any<string>()).Returns(true);
claimsPrincipal.HasClaim(Arg.Any<Predicate<Claim>>()).Returns(true);
claimsPrincipal.Identity.Returns(identity);
 
var httpContext = Substitute.For<HttpContextBase>();            
httpContext.User.Returns(claimsPrincipal);
 
var controllerContext = new ControllerContext(
    httpContext, new System.Web.Routing.RouteData(), myController);           
 
myController.ControllerContext = controllerContext;
 
// Act
var result = myController.TestMethod();
 
// Assert
// . . .

Remember that this is only necessary if you are trying to access claims based on the identity within the `TestMethod()`. Also, I’ll remind the reader that I assert only that this worked in the specific situation that I needed it to, but it’s probably a good starting point for others.

References

https://volaresystems.com/blog/post/2010/08/19/Dont-mock-HttpContext

http://nsubstitute.github.io/help/set-return-value/

https://stackoverflow.com/questions/1389744/testing-controller-action-that-uses-user-identity-name

https://stackoverflow.com/questions/13579519/mock-authenticated-user-using-moq-in-unit-testing

https://stackoverflow.com/questions/14190066/is-there-any-way-i-can-mock-a-claims-principal-in-my-asp-net-mvc-web-application

https://stackoverflow.com/questions/22762338/how-do-i-mock-user-identity-getuserid/23960592

https://dotnetcodr.com/2013/02/11/introduction-to-claims-based-security-in-net4-5-with-c-part-1/

Mock Current Date and Time in SQL Server

Occasionally, if you’re especially lucky, you’ll get into a situation where you have SQL procedures and functions that are so complicated that they require unit tests all of their own. They’ll have business logic embedded in them, and not testing them will leave a massive hole in your test coverage.

In this blog post I’m not going to describe how to do that – SSDT are quite well documented anyway. This is about how to deal with dates and times in SQL Server.

A new function

You’ll probably have a few places in your SQL script that call the following:

SELECT GETUTCDATE()

Or, you may even have the following:

SELECT GETDATE()

Which will presumably work well for what you want. Of course, the problem that you have here is, that for unit tests, this presents a variable factor in your test; that is, you’re not always testing the same procedure. Take the following segments of SQL for example:

PROCEDURE MYPROC
AS
BEGIN
	DECLARE @today DATETIME
	DECLARE @hasEntriesAfterToday INT
	
	SET @today = GETUTCDATE()

	SELECT @hasEntriesAfterToday = COUNT(*)
	FROM dbo.MyTable t
	WHERE t.Col1 > @today

	IF (@hasEntriesAfterToday > 0) 	
		select 'test'
END
GO

MyTable contains many entries after today, and my test checks that it returns ‘test’, so the test works, the code works and I’m going to bed.

But what happens in a year’s time?

Let’s say that the last entity in that table is 01/01/2015 (that way the post works in the US, too). As I write this, it is mid-way through June. So, I need to know what will happen on 2nd January 2015. If I do nothing then when it is 2nd January 2015 the test will start to fail, and I won’t know why.

Abstract the date

When faced with this problem, my initial fix was as follows:

CREATE FUNCTION dbo.MyGetDate()
RETURNS DATETIME
AS
BEGIN
	DECLARE @today DATETIME
	SET @today = GETUTCDATE()

	RETURN @today
END

And then simply change the above procedure to call this. That certainly works; however, as soon as you start to reference this function (for example, you set a default value for a date in a table), you’ll find that you’ll get stuck when you try to mock it out; consequently, you need a double layer:

CREATE FUNCTION dbo.MyGetDate2()
RETURNS DATETIME
AS
BEGIN
	DECLARE @today DATETIME	
	SET @today = GETUTCDATE()

	RETURN @today
END
GO

CREATE FUNCTION dbo.MyGetDate()
RETURNS DATETIME
AS
BEGIN
	DECLARE @today DATE	
	SET @today = dbo.MyGetDate2()

	RETURN @today
END
GO

What this then allows you to do is to replace the function of MyGetDate2 without affecting MyGetDate. This is a wrapper function to replace the DateTime:

internal static void OverrideDateTimeTest(SqlConnection cn, SqlTransaction tr, string newDateTime)
{
    string sql =
        "ALTER FUNCTION dbo.MyGetDate2(	" +
        ") RETURNS datetime " +
        "AS " +
        "BEGIN " +
        "DECLARE @value datetime " +
        "SET @value = convert(datetime, '" + newDateTime + "') "  +
        "RETURN @value " +
        "END";
 
    using (SqlCommand cmd = new SqlCommand(sql, cn, tr))
    {
        cmd.Connection = cn;
        cmd.CommandType = CommandType.Text;
        cmd.ExecuteNonQuery();
    }
}

And here’s the test:

[TestMethod]
public void MyTest()
{
    DBWrapper.OverrideDateTimeTest(cn, tr, "2014-06-10 22:30:00.000");
    Assert.AreEqual( …

The best part about this is that IN SQL SERVER DDL STATEMENTS CAN BE ROLLED BACK! Look at the following test:

-- 1
BEGIN TRAN
GO

-- 2
SELECT dbo.MyGetDate()
GO

-- 3
ALTER FUNCTION [dbo].[MyGetDate2]()
RETURNS DATETIME
AS
BEGIN
	DECLARE @today DATETIME
	SET @today = GETUTCDATE()

	RETURN @today
END
GO

-- 4
SELECT dbo.MyGetDate()
GO

-- 5
ALTER FUNCTION [dbo].[MyGetDate2]()
RETURNS DATETIME
AS
BEGIN
	DECLARE @today DATETIME
	SET @today = CONVERT(DATETIME, '2014-06-10 22:30:00.000')

	RETURN @today
END
GO

-- 6
SELECT dbo.MyGetDate()
GO

-- 7
ROLLBACK TRAN
GO

-- 8
SELECT dbo.MyGetDate()
GO

Okay – there’s a fair amount of code, but the stages are as follows (numbered):

1. Start the transaction.
2. Show the existing implementation of MyGetDate2 (in case it’s not what it should be).
3. Change MyGetDate2 to use GetUTCDate(), so it should be the same as before.
4. Check again – should still return the same as 2.
5. Change MgGetDate2 to return hard coded date.
6. Check that it now returns a hard coded date.
7. Rollback the transaction.
8. The transaction is rolled back, and so the function behaves as in 1.

Conclusion

So, we can include a date mock in our test and, should there be a problem, or when we’re finished, it all gets rolled back. Just because I’m always cautious about such things, I’ve created a test that checks that the default implementation returns the current date, but you shouldn’t need this.