TypeScript: Testing Private Members

I wrote about three years ago on how to test private member as well as last year and the year before. One article was more specific to C# and the two others more abstract and on TypeScript, but still relevant today. In this article, I’ll explain how I am testing private members without using any hack with Jest.

The goal of having private and public members is to mark a clear separation about what is restricted as internal use of the object that defines the member from what can be consumed from outside the scope of the object. The idea makes sense. The usage of the keyword “private” does not necessary. Using “private” does not work because you will not be able to test internal logic, neither mock them in your testing — it is blocked at the scope of the object.

class MyClass1 {
    private variable1: string = "init";
    public function2(p1: number, p2: number): void {
        // Code here...
        if (this.function1(p1)) {
            // More code here ...
        }
        // Code here... 
    }
    private function1(p1: number): boolean { }
}

There are some workarounds. One popular approach is to avoid testing these functions directly. The problem is that you have code that is not tested. An alternative is to test these private functions through public function. The problem is that you are using a function to proxy all the logic which make all test less “unit test” and fragile because these tests become dependant on another piece of code. If the logic of the private function remains the same, but the public function change, the code that is testing the private function will fail. It sways the simplicity into a nightmare. If the private function returns a boolean value, but the public function returns a void type, testing the return of the private function requires to understand the behavior of the public function that use it to extrapolate a behavior that corresponds to the return value. The proxy function, the public function, might be only a single one or many. When there is only a single function, the choice is limited and can push you in a corner without escape. When many functions, the selection of which one can also be problematic. In the end, the goal is to unit test, not to have many hurdles before even testing.

Another option is to cast to any and access the function. The problem is that any refactoring on the name will make the function to be “undefined.” It leads to issues of typing when the ground change that is the role of having a typed language in the first place.

describe("MyClass1", () => {
    describe("test the private function #1", () => {
        it("public proxy function", () => {
            const x = new MyClass1();
            expect(x.function2(1, 2)).toBe("????");
        });
        it("cast with any", () => {
            const x = new MyClass1() as any;
            expect(x.function1(1)).toBeTruthy();
        });
    });
});

So, if we have all these solutions with weaknesses, what is the best solution? The best solution that I have been used for a while now is this one: do not use private. Instead, you should use interface. The idea is that the concrete object will never be used directly, hence can have its members public. The usage across the whole application is done with an interface that exposes the members that the consumers can interact. Here is the same code as above but with the pattern of using an interface instead of private.

interface IMyClass1 {
    function2(p1: number, p2: number): void;
}

class MyClass1 implements IMyClass1 {
    private variable1: string = "init";
    public function2(p1: number, p2: number): void {
        // Code here...
        if (this.function1(p1)) {
            /// More code here ...
        }
        // Code here... 
    }
    public function1(p1: number): boolean { }
}

describe("MyClass1", () => {
    let x: MyClass1;
    beforeEach(() => {
        x = new MyClass1();
    });
    describe("function1 with an integer", () => {
        it("returns true", () => {
            expect(x.function1(1)).toBeTruthy();
        });
    });
});

It works perfectly in term of testability. The unit test code has access to all members because everything is public. It is easy to invoke all members directly but also to mock these and still keep and the type from TypeScript. In the application, we use the interface everywhere. The only place where we use the concrete class is during the initialization. Every declaration uses the interface — no exception.

Furthermore, a class is easily mockable with framework because you can access every public function and assign them a mock/spy/stub that allows to control specific branches of the code as well as managing the scope of the test to be as much as a single unit. The key of an efficient test is to have every block of code tested as a unit and then moving from bottom to top with more and more integration tests.

describe("MyClass1", () => {
    let x: MyClass1;
    beforeEach(() => {
        x = new MyClass1();
        x.function1 = jest.fn();
    });
    describe("function2", () => {
        it("calls function1", () => {
            x.function2(1,2);
            expect(x.function1).toHaveBeenCalledTimes(1);
        });
    });
});

Last but not the least, functions that are directly sitting in a module are very hard to unit test. It is not possible to mock or spy their dependencies. The lack of access sway my design to always encapsulate every function into a class.

In summary, encapsulation does not require to rely solely on public, private and protected keywords. The usage of an interface is powerful by adding the protection to what can be accessed while allowing developers to have a sane and simple way to test correctly without using a detour to obtain the desired piece of code.

Unit Tests and Coverage Report in Jenkins using Jest from Create-React-App

Since I left Microsoft Visual Studio Online (VSTS) has an employee I have been using Jenkins which is the continuous integration (ci) platform Netflix uses. I configured two Jenkins jobs for the project I am leading. One is handling every pull request done against master and the second one is executed during the merge of any pull request into master. For many months, I didn’t have the unit tests running on the platform. The reason is that I am, yet, used to how Jenkins works and even after several months feel VSTS more intuitive. Regardless, recently I took the time and setup to have my TypeScript code using Create-React-App to run my unit tests in these two Jenkins tasks. I am using Create-React-App, which come with the best testing framework I have experimented so far which is Jest. My goal was to have all the unit tests ran as well as to see the coverage.

Here are the steps required to have Jenkins handle your test. First thing is to install a dev dependency to “jest-junit”. The reason is that we need to convert the format of Jest into Junit.

npm install --save-dev jest-junit

The next step is to download a Python script in your repository. I have mine in “tools”. The reason is also about converting. Jest coverage file is not in the right format. The Python script converts the locv into Cobertura format. You can download once the script at this address.

wget https://raw.github.com/eriwen/lcov-to-cobertura-xml/master/lcov_cobertura/lcov_cobertura.py

Few configurations are required in the package.json. The first one is to create a test command that Jenkins execute instead of the default test command. The command calls the react-scripts. I am using TypeScript, hence I have to use the react-scripts-ts command. The next parameter is the “test” command which we still want to execute. The change starts with the test results processor. This is where you specify the jest-junit to execute once the tests are done. I set my coverage to be positioned into the “coverage” folder which is the folder I have ignored in the .gitignore and where I have normally my local coverage file outputted. Here are the three commands I have. The first one runs the test, the second run and coverage for the ci (this is the new stuff) and the last one is when I want to run locally the coverage.

"test": "react-scripts-ts test --env=jsdom",
"test:ci": "react-scripts-ts test --env=jsdom --testResultsProcessor ./node_modules/jest-junit --coverage --coverageDirectory=coverage",
"coverage": "react-scripts-ts test --env=jsdom --coverage",

Finally, you need few jest-unit configurations. This can be in your package.json. I have some coverage folder that I want to exclude which you can do in the jest configuration under collectCoverageFrom. I had these before doing the task we are doing of configuring Jenkins. Then, the coverage reported must be lcov and text. Finally, the new configurations are under “jest-junit”. The most important configuration is the “output” which is again in the coverage folder. You can change the destination and file as you wish. However, remember the location because you will need to use the same in a few instants inside Jenkins.

  "jest": {
    "collectCoverageFrom": [
      "**/*.{ts,tsx}",
      "!**/node_modules/**",
      "!**/build/**",
      "!**/definitionfiles/**",
      "!**/WebWrokers/**",
      "!**/*.mock.ts",
      "!src/setupTests.ts"
    ],
    "coverageReporters": [
      "lcov",
      "text"
    ]
  },
  "jest-junit": {
    "suiteName": "jest tests",
    "output": "coverage/junit.xml",
    "classNameTemplate": "{classname} - {title}",
    "titleTemplate": "{classname} - {title}",
    "ancestorSeparator": " > ",
    "usePathForSuiteName": "true"
  },

In Jenkins, you need to add 2 build steps and 2 post-build steps. The first build step is to run the unit test with the script we just added in the package.json. The type of build step is “Execute Shell”.

npm run test:ci

The second step is also an “Execute Shell”. This one calls the python code that we placed in the “tools” folder. It is important to change the path of your lov.info and coverage.xml. Both are in my “/coverage/” folder. The “base-dir” is the directory of the source of your code.

python tools/lcov_cobertura.py coverage/lcov.info --base-dir src/ --output coverage/coverage.xml

The next two steps are “Post-Build”. This time, two different types. The first one is “Publish JUnit test result report”. It has a single parameter which is the XML file. Mine is set to “coverage/junit.xml”. The second task is a “Publish Cobertura Coverage Report”. It also takes a single parameter which is the coverage.xml file. Mine is set to “coverage/coverage.xml”.

At that point, if you push the modification from the package.json and the Python script you will see Jenkins running the unit tests and doing the conversion. It is possible to adjust the threshold of how many tests your allow to fail to not break the build as well as setting the percentage of coverage you expect. You will get a report on the build history that allows you to sort and drill into the coverage report.

How to unit test private method in TypeScript (part 2)

I already posted about how to write unit tests for private method with TypeScript about one year ago. Few days ago, I had the same discussion that I had in my previous team concerning private method. The situation is similar. Developers don’t test private method and rely on public method to reach those private methods. At first, it may sound that we are going inside those private methods, therefore we are doing proper unit testing.

The problem by going through intermediate methods to access the one we want to test is that any change on intermediate methods will make multiple test to fail. When a unit tests fail, the goal is to know which unit of your code is failing. Imagine the situation where you have class A that has method a1, a2, a3. You want to to unit test a3, but the only entry point is a1 which is the only method public. This one call a2, who call in some particular situation a3. You have multiple conditions in a3 and you evaluate that you need 5 unit tests. The problem is that if a1 or a2 change in the future that all these 5 tests may fail, when they should not.

At that point, most people understand the situation and agree to test the private methods. However, there is some good ways to do it and some bad ways. The worst way to do it to cast the class A to be of type any and call a3 directly. Something like :

// Bad way:
var a = new A();
(a as any).a3();

The problem with the above code is that when you will refactor a3 to have a better name that no tool will find out this instance. More, this open the door to access private fields or inject new functions and fields to the class. At the end, it become a nightmare to maintain. We are using TypeScript to be strongly typed, our tests should continue to be as strong.

In the previous article I wrote, I talked about 2 patterns. The first one is about working around encapsulation with an interface. The second had two variations.

Let’s remember the first pattern. The first pattern is that class A should have an interface IA that is used everywhere. IA would only expose the method a1. Everywhere you use the interface and the only place where it doesn’t it’s when it’s getting injected by the inversion of control container. However, we can leverage this abstraction to keep a strong encapsulation for the application and use the implementation that has every method public. This way, developers still have only access to a1 in our example, but in our test we have access to everything else. This might not sound a proper solution at first since we open the encapsulation on the implemented class, but it’s the cheapest way to be able to test unit tests. That said, I am all with you that there is other solution like the pattern #2 presented in the previous article.

The second pattern presented was about moving code around. In our example, a2 and a3 are private and could be moved outside an other class. For example, let’s say that A was a user class, a1 was a method to get the user information to display to the screen, a2 a method to get the address information and a3 a method to format the street address. This could be refactored from :

class User{
    public getUserInformationToDisplay(){
        //...
        this.getUserAddress();
        //...
    }

    private getUserAddress(){
        //...
        this.formatStreet();
        //...
    }
    private formatStreet(){
        //...
    }
}

to:

class User{
    private address:Address;
    public getUserInformationToDisplay(){
        //...
        address.getUserAddress();
        //...
    }
}
class Address{
    private format: StreetFormatter;
    public format(){
        //...
        format.ToString();
        //...
    }
}
class StreetFormatter{
    public toString(){
        // ...
    }
}

Originally, we wanted to test the private method formatStreet (a3), and now it’s very easy because I do not even need to care about all the classes or function that call it, just to unit test the StreetFormatter class (which was the original a3). this is the best way to unit test private method : to divide it correctly into specific class. This is also costly in term of time.

I always prefer the second approach, but time constraints and the high velocity of shipping features is always that is a higher priority — even in software shop where the message is quality first. That said, I prefer using the first approach than not having any unit tests at all. It’s a good compromise that work well what ever your framework. I used both approach in TypeScript code that was using proprietary framework, as well with React and now with Angular. At the end, the important is to have the best coverage while being sure that everything tested are solid to help the software and not slow down the whole development.

How many unit tests should you write?

I always found automated tests very powerful. On the long run, you accumulate a lot of values by having a fast way to see if something has changed that wasn’t originally planned. It serves as a good living documentation (if tests are simple to understand). The current trend in the industry is to rely solely on automated tests. Whence, all tests need to be well written. Writing good unit tests is something that is harder that you can think. Since the last 2 years, I have been in multiple teams and I realized that most people do not really know how to unit test properly.

One thing that need to be clear is that even if you touched a line with a test, it doesn’t mean that this one doesn’t need to be touched by multiple tests. I see often people running code coverage to know if they are done or not when testing. That is wrong.

A second thing is that each method needs different amount of test depending of the complexity of those ones. You cannot have only one successful unit test, and one failure unit test and be done with your method.

Another concept that seem to be not understood is that even if you “know” that the value in parameter will never be null, you have to test it for null if you allow it. You cannot discriminate scenario because you know what is the current use of the code.

There is also the notion of the coverage not being a good metric to know if you have a well written plan. While I agree that 100% doesn’t mean 100% free bug, I do not agree that it’s acceptable to have 50% of coverage. If your software quality bar is to have only 50% of your code tested, than it means that you are not ready to not have human to test your software. In fact, you should probably test your code to have above 100% coverage — multiple lines will get hit per multiple tests.

Assertions is also debatable. Most of the time, people are asserting a lot of variable which make the test hard to maintain. Every tests should assert a minimum set of variable. In fact, you should aim to assert a specific scenario. If you are asserting a lot, than you are probably testing more than one thing, thus not testing a unit but a batch. Some exception are clear, for example, testing to map a class to another class. However, a rule of thumb is to identify these big tests and make them smaller by dividing the actual code into several methods.

Preparing your unit tests should be clean. You shouldn’t have to write 20 lines of code in each of your test to create your scenario to test. Divide that arrange code into builder class. This way, they can be reused across several tests. A bonus is that by doing so, you can use those building method to seed your development database.

Naming your test is something important. The reason is that other developer won’t be able to find specific scenario and might duplicate test or not look at them. If you have thousand and thousand of tests, it become even more important. I like following the name with GivenXXX_WhenXXX_ThenXXX. It forces to have a structure of Given a specific case When specific configuration is provided Then you expect a specific result.

Here is a simple code. How many test should be created?

public class SimpleCode
{
    public string Value { get; set; }  

    public SimpleCode Merge(SimpleCode parameter)
    {
        var mergedObject = new SimpleCode();
        if (parameter.Value != null || this.Value != null)
        {
            mergedObject.Value = parameter.Value ?? this.Value;
        }
        return mergedObject;
    }
}

Most people might see two or three tests, but the answer is six.

[TestMethod]
    public void GivenSimpleCode_WhenMainInstanceValueNull_AndParameterValueNull_ThenValueNull()
    {
        // Arrange
        var mainInstance = new SimpleCode() {Value= null};
        var simpleCodeParameter = new SimpleCode() { Value = null };

        // Act
        var result = mainInstance.Merge(simpleCodeParameter);

        // Assert
        Assert.IsNull(result.Value);
    }

    [TestMethod]
    public void GivenSimpleCode_WhenMainInstanceValueNotNull_AndParameterValueNull_ThenMainInstanceValue()
    {
        // Arrange
        const string VALUE = "Test";
        var mainInstance = new SimpleCode() { Value = VALUE };
        var simpleCodeParameter = new SimpleCode() { Value = null };

        // Act
        var result = mainInstance.Merge(simpleCodeParameter);

        // Assert
        Assert.AreEqual(VALUE, result.Value);
    }
    
    [TestMethod]
    public void GivenSimpleCode_WhenMainInstanceValueNull_AndParameterValueNotNull_ThenParameterValue()
    {
        // Arrange
        const string VALUE = "Test";
        var mainInstance = new SimpleCode() { Value = null };
        var simpleCodeParameter = new SimpleCode() { Value = VALUE };

        // Act
        var result = mainInstance.Merge(simpleCodeParameter);

        // Assert
        Assert.AreEqual(VALUE, result.Value);
    }

    [TestMethod]
    public void GivenSimpleCode_WhenMainInstanceValueNotNull_AndParameterValueNotNull_ThenValueParameterValue()
    {
        // Arrange
        const string VALUE1 = "Test1";
        const string VALUE2 = "Test2";
        var mainInstance = new SimpleCode() { Value = VALUE1 };
        var simpleCodeParameter = new SimpleCode() { Value = VALUE2 };

        // Act
        var result = mainInstance.Merge(simpleCodeParameter);

        // Assert
        Assert.AreEqual(VALUE2, result.Value);
    }

    [TestMethod]
    [ExpectedException(typeof(NullReferenceException))]
    public void GivenSimpleCode_WhenParameterNull_ThenException()
    {
        // Arrange
        var mainInstance = new SimpleCode();
        SimpleCode simpleCodeParameter = null;

        // Act & Assert
        mainInstance.Merge(simpleCodeParameter);
    }


    [TestMethod]
    public void GivenSimpleCode_DefaultValue_ValueNull()
    {
        // Arrange & Act
        var mainInstance = new SimpleCode();

        // Assert
        Assert.IsNull(mainInstance.Value);
    }
}

Often, people do not test the default value of a class. This is something everyone should do. What happen if at some point a default value change but was required to be a specific value depending of the scenario. Without this test, you are not notified that something is breaking from the expected value. In that example, the expected value is NULL. If someone change it to an empty string, this might break other scenario that rely to compare on NULL to determine some state. Another testing scenario that I see often is about passing wrong value has parameter. In that particular example, null will break and return a null reference exception. Creating the test make you realize that you should probably handle that case and have a better code, like the following one:

public SimpleCode Merge(SimpleCode parameter)
{
    if (parameter == null)
    {
        throw new ArgumentNullException(nameof(parameter));
    }
    var mergedObject = new SimpleCode();
    if (parameter.Value != null || this.Value != null)
    {
        mergedObject.Value = parameter.Value ?? this.Value;
    }
    return mergedObject;
}

In that case, I just thrown an exception and will need to assert that particular exception. Why is that better than just having the null reference exception. For three reasons, first, it’s clear that it shows that the null parameter is a known scenario. Second, today it’s an exception, tomorrow it could be that we return a value. A change will make this particular test that expect a specific exception to become red and thus having a change in the test. The third reason is that if another exception is thrown, that I’ll get an error. I expect to only have an argument null exception, not a null reference or an overflow. Any other cases will be considered a bug, not the one handled.

How many test should your write? As many as your code required. Is that time consuming? Of course. Automated tests take about 30-50% of the development time when well done. Your code base will have has many line of code for tests and for code. That is the cost of being able to run a lot of test multiple times per day as well as not having human resource to test. It’s worth it because all these scenarios are hard to test for a human and since these tests are supposed to be fast, that you can run them often. The gain is enormous as the size of your code base increase. Your confidence in changing your code should remain high and new developer coming into the team won’t be afraid to change something that disrupt the expectation. That said, I still strongly believe that automated tests should be paired with human testing before being released into the public, but this is another story. You can download and play with the code in this Git Hub repository.

How to have MsTest localized by Attribute?

Working with multiple languages requires to test in multiple languages too. A simple use case is if you have custom Asp.Net routing that you might want to test where an English route goes and the same for a French one. This goes beyond just text, but also how to handle numbers and datetime. The traditional way to do unit test in multiple localisations is to set the current thread at the beginning of the test, do the logic, assert and set the thread back to the original value.

The problem is that in all your code you need to set the thread manually. It would be better to have an attribute on the top of the test method and have this one handling the thread culture. Unfortunately, MSTest “TestMethod” attributes is sealed which mean you cannot inherit of this one. The work around is to create a custom attribute. However, this come with the challenge to hook into MsTest pipeline to have MsTest reads the attribute and act accordingly. This is what we will discuss in this article, how to use ContextAttribute, IMessageSink, IContributeObjectSink and so on.

First, let’s create a standard attribute that we will use on top of our test that need localization. We will use this one in combination of the TestMethod. The use will looks like this:

[TestMethod]
[LocalizedTest(LocalizedSection.EN_NAME)]
public void MyTest()
{
    //... Your test
}

The attribute has a parameter which is the Culture Name that we want to have the thread. The culture name is “en-us” for USA English or “fr-ca” Canadian French.

public class LocalizedTestAttribute:Attribute
{
    public string CultureName {get; set;}
    public LocalizedTestAttribute(string cultureName)
    {
        this.CultureName = cultureName;
    }
}

A second attribute is required to be at the top of the class tested. This is the way to notify the Microsoft test framework that we want to hook inside the pipeline of tasks that the testing framework is going while executing tests. This attribute inherit from ContextAttribute, from System.Runtime.Remoting.Contexts namespace. The role of that class is to define a collection of possible hooks. In that case, we have only one hook that we call LocalizedTestMessage. Those hooks are called “messages”. I am using a helper named TestProperty which handle generic code for every message. This generic class is inspired by the MsTestExtension source code.

public class LocalizedTestContextAttribute: ContextAttribute
{
    public LocalizedTestContextAttribute():base("LocalizedTest")
    {

    }

    public override void GetPropertiesForNewContext(IConstructionCallMessage msg)
    {
        if (msg == null)
            throw new ArgumentNullException("msg");
        msg.ContextProperties.Add(new TestProperty<LocalizedTestMessage>()); //We add 1 new message into the test pipeline
    }
}

public class TestProperty<T> : IContextProperty, IContributeObjectSink where T : IMessageSink, ITestMessage, new()
{

    private readonly string _name = typeof(T).AssemblyQualifiedName;

    [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
    public bool IsNewContextOK(Context newCtx)
    {
        return true;
    }


    [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
    public void Freeze(Context newContext)
    {
    }


    public string Name
    {
        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
        get { return _name; }
    }


    [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
    public IMessageSink GetObjectSink(MarshalByRefObject obj, IMessageSink nextSink)
    {
        T testAspect = new T();
        testAspect.AddMessageSink(nextSink);
        return testAspect;
    }
}

public interface ITestMessage
{
    void AddMessageSink(IMessageSink messageSink);
}

Finally, we need to have our LocalizedTest message hook (message) defined. This class defines what is done before and after the execution of the test. This class is able to access the tested method to check if LocalizedTest attribute is defined on the class. If yes, it proceeds, otherwise it executes the method without changing anything. When the attribute is present, it backup the current thread culture, get the culture name from the attribute and set it to the test thread. It executes the test, and set back the original thread.

public class LocalizedTestMessage : BaseTestMessage<LocalizedTestAttribute>, IMessageSink, ITestMessage
{
    private IMessageSink nextSink;

    [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
    public IMessage SyncProcessMessage(IMessage msg)
    {
        if (msg == null)
            throw new ArgumentNullException("msg");
        CultureInfo currentCultureInfo = null;
        CultureInfo currentUICultureInfo = null;

        //Before test get value to set back after test
        LocalizedTestAttribute localizationAttribute = base.GetAttribute(msg);
        if (localizationAttribute != null)
        {
            currentCultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
            currentUICultureInfo = System.Threading.Thread.CurrentThread.CurrentUICulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(localizationAttribute.CultureName);
            System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture;
        }

        //Execute test
        IMessage returnMessage = nextSink.SyncProcessMessage(msg);

        //After test set back value
        if (localizationAttribute != null && currentCultureInfo!= null && currentUICultureInfo!=null)
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = currentCultureInfo;
            System.Threading.Thread.CurrentThread.CurrentUICulture = currentUICultureInfo;
        }
        return returnMessage;
    }

      
    [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
    public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
    {
        throw new InvalidOperationException();
    }

    public IMessageSink NextSink
    {
        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
        get
        {
            return nextSink;
        }
    }

    public void AddMessageSink(IMessageSink messageSink)
    {
        nextSink = messageSink;
    }
}

public abstract class BaseTestMessage<TAttribute> where TAttribute : Attribute
{

    [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
    protected TAttribute GetAttribute(IMessage message)
    {
        string typeName = (string)message.Properties["__TypeName"];
        string methodName = (string)message.Properties["__MethodName"];
        Type callingType = Type.GetType(typeName);
        MethodInfo methodInfo = callingType.GetMethod(methodName);
        object[] attributes = methodInfo.GetCustomAttributes(typeof(TAttribute), true);
        TAttribute attribute = null;
        if (attributes.Length > 0)
        {
            attribute = attributes[0] as TAttribute;
        }
        return attribute;
    }
}

It would be even better if we could avoid having two different attributes on each test but this is a solution that still let us avoid having to handle thread on every test. It’s also important to notice that this is only good for MsTest. If you are using other testing framework like nUnit or xUnit that this will not work. However, these frameworks have other mechanism to handle pre and post tests too. The documentation is very slim on Microsoft about there infrastructure classes. It comes from a pre-era where Microsoft where less open that it is now.

How to unit test private method

This is something that I got asked from little start-up up to Microsoft. How to you test private method? I often see horrible things. For example, if your class as 1 public method that call 5 privates method and you want to unit test 1 of the 5 methods, calling the public method to do so is wrong. Something can change anywhere in the class and break that test. Also, creating test this way is painful because it takes time to setup all variables to value that make all others method not fail. Once you reach the method you want to test you can start really testing what you are there for. An other horrible thing is to start using advanced shimming stuff that rely on reflection. The solution is simple : create more cohesive classes.

I think an example is better before continuing about how to divide code to help creating more efficient unit test. Here is a snippet that illustrate many problem. We have an Order class that has a list of item that can be bought. At some point, we want to pass a transaction so we have a method called Purchase which return the list of item that we can really purchase based on different business logic. For example, we allows only item that is between 0$ and 100$ to be bought, only item that is not discontinued, we can only buy 1 item of any kind per transaction, not more than 3 items at the same time can be in the basket and finally nothing above an order of 50$ is allowed (so we only add item to be purchase under 50$).

public class ShoppingBasket
{
    public List<Item> Items { get; set; }

    public List<Item> Purchase()
    {
        var canBeBought = new List<Item>();
        foreach (var item in Items)
        {
            bool canBuy = true;
            if (item.Money < 0 || item.Money > 100)
            {
                canBuy = false;
            }

            if (item.IsDiscontinued)
            {
                canBuy = false;
            }

            if (!this.IsUnique(item.Id))
            {
                canBuy = false;
            }

            if (this.IsShoppingBasketFull())
            {
                canBuy = false;
            }

            if (this.HasReachMaximumAmountPerOrder(canBeBought))
            {
                canBuy = false;

            }
            if (canBuy)
            {
                canBeBought.Add(item);
            }
        }
        return canBeBought;
    }

    private bool IsUnique(int id)
    {
        return this.Items.Count(d => d.Id == id) > 1;
    }

    private bool IsShoppingBasketFull()
    {
        return this.Items.Count >= 5;
    }

    private bool HasReachMaximumAmountPerOrder(List<Item> canBeBought)
    {
        return canBeBought.Sum(d=>d.Money) > 50;
    }
}

public class Item
{
    public int Id { get; set; }

    public double Money { get; set; }

    public bool IsDiscontinued { get; set; }
}

If you want to test if the Lambda expression is well formed for the IsUnique method, you will have to create a list of items and pass it to the ShoppingBasket class. So far, this is fine. However, you cannot call the method IsUnique because this one is private. You have two choices. You break the encapsulation of the ShoppingBasket by changing the visibility from private to public or you refactor your class to something more testable, more cohesive and more object oriented. Changing the encapsulation is fine. In fact, in that case it does not really matter because it does not disrupt the system. Someone could call IsUnique any time and it does not change any operational flow. However, is it really the responsability of the ShoppingBasket to handle the unique?

Let’s start trying to unit test this actual code to illustrate how it is not a good idea to test through the public method to reach a private method.

[TestMethod]
public void TestIfIsUniqueMethodWorksWhenListHasNotUniqueItem()
{
    // Arrange
    var shoppingBasket = new ShoppingBasket();
    var item1 = new Item() {Id = 1, IsDiscontinued = false, Money = 5};
    var item2 = new Item() {Id = 2, IsDiscontinued = false, Money = 10};
    var item3 = new Item() {Id = 3, IsDiscontinued = false, Money = 50};
    var item4 = new Item() {Id = 1, IsDiscontinued = false, Money = 5};
    shoppingBasket.Items = new List<Item> {item1, item2, item3, item4};

    // Act
    var itemThatWeCanPurchase = shoppingBasket.Purchase();

    // Assert
    Assert.AreEqual(2, itemThatWeCanPurchase.Count);
}

You will tell me that this is fine. In fact, it is. In that case the problem is not the amount of preparation. It is often the case, but not that time. The problem is that if tomorrow the threshold of 50$ go down to 10$ that this unit test will fail. Right now, the item id 2 and 3 are returned but if this limit goes from 50$ to 10$ than the id 2 is out which will return only one item. The unit test about unique fail because of the maximum amount per order. This is wrong.

A unit test must test a unit. It has to test a single thing. It has to be atomic. This is why we need to refactor that code.

The first thing to do is to ask who is the expert of the field for each logic. The first logic concern the logic about that we can only buy item with money between 0$ and 100$. This raise multiple questions.

  1. Is it a shopping basket logic?
  2. Does that logic is universal on the software we are building or just for specific case? Does this range may change during the lifetime of this software?
  3. Do we have different kind of Item?

The first question make sense. Maybe depending of the type of shopping basket that logic can change. For example you could have “SmallShoppingBasket” and a “BigShoppingBasket” and depending of the basket the threshold change. This is why we cannot build a software without knowing the specification: the code changes depending of what are the rules. Creating a generic system for all case increase the time to build this one by a huge magnitude of time. That said, for that first condition, we need to extract that code out of the loop in all case. The reason is that this condition is independent of all items — it is a condition on a single item. Since we are not planning to have multiple basket and the amount belong to an item, for that use case, it makes sense to set the condition inside the Item class. This change result having one more method in Item and the unit test to call that method.

public class Item
{
    public int Id { get; set; }

    public double Money { get; set; }

    public bool IsDiscontinued { get; set; }

    public bool IsPriceLegitForPurchase()
    {
        return this.Money < 0 || this.Money > 100;
    }
}

The second condition is checking if the item is discontinued. The call is already on the item which is great. However, already have a condition on the item done one line above since our last refactoring on the price.

foreach (var item in Items)
{
    bool canBuy = true;
    if (!item.IsPriceLegitForPurchase())
    {
        canBuy = false;
    }

    if (item.IsDiscontinued)
    {
        canBuy = false;
    }
    // ...

Instead of calling twice the item we should think. These two operations has something in common: it validates the item for purchase. We should have a method in the item that does that for us. Not only it will self-document what it is going on but that logic could be reused later without having to duplicate both calls. We end up having a single validation method for purchase in item.

public bool IsValidForPurchase()
{
        if (!this.IsPriceLegitForPurchase())
        {
            return false;
        }

        if (this.IsDiscontinued)
        {
            return false;
        }
    return true;
}

The test is also clearer.

//...
if(!item.IsValidForPurchase())
{
   canBuy = false;
}
//...

The third condition was to check if the shopping basket is full. The logic belong to the basket because this one is the one who know its size, which is 5. The problem is that when we will test that logic, we do not want to have to create items that necessary pass condition for “IsValidForPurchase” method. We just want to create a list of item and test the count. That said, this is a perfect case that this method should be public.

The next condition is about if the list of item that is valid to purchase has still some place to add additional item. This is an interesting case. This logic does not belong to item, it belongs to the list. It means that this list is an entity which some properties, states, etc.

public class ItemValidToPurchase : List<Item>
{
    public bool HasReachMaximumAmountPerOrder()
    {
        return this.Sum(d => d.Money) > 50;
    }
}

The condition in the Shopping Basket is just to call the method.

if (canBeBought.HasReachMaximumAmountPerOrder())
{
    canBuy = false;
}

So the final code looks like this for the test about unique.


private ShoppingBasket GetShoppingBasket()
{
    var shoppingBasket = new ShoppingBasket();
    var item1 = new Item() {Id = 1, IsDiscontinued = false, Money = 5};
    var item2 = new Item() {Id = 2, IsDiscontinued = false, Money = 10};
    var item3 = new Item() {Id = 3, IsDiscontinued = false, Money = 20};
    var item4 = new Item() {Id = 1, IsDiscontinued = false, Money = 5};
    shoppingBasket.Items = new List<Item> {item1, item2, item3, item4};
    return shoppingBasket;
}

[TestMethod]
public void TestIfIsUniqueMethodWorksWhenListHasNotUniqueItem()
{
    // Arrange
            var shoppingBasket = this.GetShoppingBasket();

    // Act
    var isUnique = shoppingBasket.IsUnique(1);

    // Assert
    Assert.IsFalse(isUnique);
}

[TestMethod]
public void TestIfIsUniqueMethodWorksWhenListHasUniqueItem()
{
    // Arrange
    var shoppingBasket = this.GetShoppingBasket();

    // Act
    var isUnique = shoppingBasket.IsUnique(2);

    // Assert
    Assert.IsTrue(isUnique);
}

And the classes code look.

public class Item
{
    public int Id { get; set; }

    public double Money { get; set; }

    public bool IsDiscontinued { get; set; }

    public bool IsPriceLegitForPurchase()
    {
        return this.Money < 0 || this.Money > 100;
    }

    public bool IsValidForPurchase()
    {
            if (!this.IsPriceLegitForPurchase())
            {
                return false;
            }

            if (this.IsDiscontinued)
            {
                return false;
            }
        return true;
    }
}
public class ItemValidToPurchase : List<Item>
{
    public bool HasReachMaximumAmountPerOrder()
    {
        return this.Sum(d => d.Money) > 50;
    }
}
public class ShoppingBasket
{
    public List<Item> Items { get; set; }

    public ItemValidToPurchase Purchase()
    {
        var canBeBought = new ItemValidToPurchase();
        foreach (var item in Items)
        {
            bool canBuy = true;
            if(!item.IsValidForPurchase())
            {
                canBuy = false;
            }

            if (!this.IsUnique(item.Id))
            {
                canBuy = false;
            }

            if (this.IsShoppingBasketFull())
            {
                canBuy = false;
            }

            if (canBeBought.HasReachMaximumAmountPerOrder())
            {
                canBuy = false;
            }

            if (canBuy)
            {
                canBeBought.Add(item);
            }
        }
        return canBeBought;
    }

    public bool IsUnique(int id)
    {
        return this.Items.Count(d => d.Id == id) == 1;
    }

    public bool IsShoppingBasketFull()
    {
        return this.Items.Count >= 5;
    }
}

As you can see, the condition has changed on the IsUnique method. Because and error was present and only could have been detected with a valid set of unit test on that method. We could go even further by refactoring even more this code. I’ll write a second post about what we could have done with a more flexible code that allow to have dynamic validation using other design pattern.

You can find the initial code and the final code in this Git Repository.

How to unit test JQuery fadeIn and fadeOut with Qunit

I wasn’t unit testing much my client side code until I joined Microsoft. Most of the time to reason was the time and also that most of the web application I was working on did not require to have this degree of testing. Since I am working in a division that does not have testers we have to have a bigger coverage. In JavaScript, it is possible to hide html element with JQuery with fadeOut and make them reappears with fadeIn. Under the hood, it just do an animation that has the final result to have a style that display to none or to display block the control. Nevertheless, in some scenario you want to unit test if in a particular condition the html element is really there or not.

This can be done easily with Qunit and SinonJs. Qunit is the JQuery JavaScript unit test framework and SinonJs is a mock/stub/fake library. For the purpose of this article, I will not explain how Qunit and SinonJs works but concentrate on the fact that you cannot simply invoke something that move in time and expect to assert right away. The reason is simple : the animation takes time to be completed.

test("should animate element over 500ms", function () {
    var el = jQuery("<div></div>");
    el.appendTo(document.body);
    ok(el.css('display').indexOf("block") > -1);
    el.fadeOut();
    ok(el.css('display').indexOf("none") > -1);
  
});

This test fail on the second assertion. The reason is that fadeOut is not yet done and we are already asserting the display which is still to block. We need to play with the time. We need to fake the time to something in the future. This is where SinonJs come to the rescue.

test("should animate element over 500ms", function () {
    var el = jQuery("<div></div>");
    el.appendTo(document.body);
    ok(el.css('display').indexOf("block") > -1);
    el.fadeOut();
    this.clock.tick(510);
    ok(el.css('display').indexOf("none") > -1);
  
});

testpass

It is possible to add some tick to the testing framework. To do so, use the clock property and use the tick function. The parameter takes the time in millisecond you want to move forward. If you check the Date of the browser, you will notice that this has a direct impact of the date time. You can call that method as many time you need. In the example, I have used 510 milliseconds because the default fadeOut method takes 500 ms. The end result is that this unit test pass. You can see that demo working on that JSFiddle.

This way to unit test fadeIn and fadeOut works with any kind of JQuery animation and also any code that require some time in JavaScript. You can use it if you are using JQuery UI libary too.

Unit Testing MVC Area Route Mapping to Controller and Url Creation

One of the key element of your website should be that every Url that you have should goes to the controller’s action that you expect. This is also true when you are using an Asp.Net Html Helper that generate an URL. To be sure that you can rely that an Url links to the right action and that every Url generated have the right string structure, you must unit test them. This is far more important when your project start to become bigger and bigger. Routing rules can override a previous route and create unreachable code from your web interface. To solve that issue, every routes should be unit tested.

UnitTestControllerRouting

Asp.Net MVC routing system is quite interesting and easy to unit tests. I read that it is hard to unit test but this is not my experience. In this article, I will show you how to unit test routing from a specific AreaRegistration file. This is exactly the same process if you have your route inside the RouteConfig.cs file. Instead of using the area class, you use the RouteConfig class. They both use the System.Web.Routing.RouteTable and this is what we need to setup tests.

So before going into the detail, here is an example to unit test and Url to a controller’s action.

[TestMethod]
public void GivenRouteForContest_WhenPortefolioId()
{
    // Arrange
    string url = Constants.Areas.CONTEST + "/1/Portefolio/2";

    // Act
    RouteData routeData = base.GetRouteDataForUrl(url).RouteData;

    // Assert
    Assert.IsNotNull(routeData);
    Assert.AreEqual("Portefolio", routeData.Values[Constants.RoutePortionName.CONTROLLER]);
    Assert.AreEqual("IndexById", routeData.Values[Constants.RoutePortionName.ACTION]);
    Assert.AreEqual("1", routeData.Values[Constants.RoutePortionName.ACTIVE_CURRENT_CONTEST_ID]);
    Assert.AreEqual("2", routeData.Values[Constants.RoutePortionName.ACTIVE_CURRENT_PORTEFEOLIO_ID]);
}

As you can see by this unit test example, the url is defined in the arrange section. The act part is a one liner that call a method that act as a proxy to call the real GetRouteData. To have access to that method, all my routing tests inherit from a testing class that allows me to call. I named that class RouteTestBase. It has a method is running between code which clear all routes and configures the route. This is where I have setup the configuration of the area I wanted to test. This is where you may want to use the global route configuration. This class has two public methods. The first one is used for unit testing string url to route data and the second one is to test Html Url helper to generate the string url.

public class RouteTestBase
{
    [TestInitialize]
    public void BetweenTest()
    {
        RouteTable.Routes.Clear();
        var areaRegistration = new ContestAreaRegistration();
        var areaRegistrationContext = new AreaRegistrationContext(areaRegistration.AreaName, RouteTable.Routes);
        areaRegistration.RegisterArea(areaRegistrationContext);
    }

    /// <summary>
    /// From URL to Controller/Action, this method return the route and http context after passing the URL
    /// into the RouteTable.
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    protected RouteAndContext GetRouteDataForUrl(string url)
    {
        var context = FakeHttpContext(requestUrl: "~/" + url);
        RouteData routeData = RouteTable.Routes.GetRouteData(context);
        return new RouteAndContext(context, routeData);
    }

    /// <summary>
    /// Generate an UrlHelper to be used to generate URL string. 
    /// </summary>
    /// <param name="appPath">Define the application path. By default, if all routing start from the domain than this should not be set.</param>
    /// <returns>Html</returns>
    protected UrlHelper GetUrlHelper(string appPath = "~/")
    {
        HttpContextBase httpContext = FakeHttpContext(appPath:"/",requestUrl: appPath);
        var routeData = RouteTable.Routes.GetRouteData(httpContext) ?? new RouteData();
        RequestContext requestContext = new RequestContext(httpContext, routeData);
        UrlHelper helper = new UrlHelper(requestContext, RouteTable.Routes);
        return helper;
    }

    private HttpContextBase FakeHttpContext(string appPath="~/", string requestUrl = "/")
    {
        // Mocks
        var context = new Mock<HttpContextBase>();
        var request = new Mock<HttpRequestBase>();
        var response = new Mock<HttpResponseBase>();
        var session = new Mock<HttpSessionStateBase>();
        var server = new Mock<HttpServerUtilityBase>();
        var user = new Mock<IPrincipal>();
        var identity = new Mock<IIdentity>();

        // Query String Parameters
        var routePart = requestUrl;
        var queryStringPart = requestUrl;

        if (routePart.Contains("?"))
        {
            var indexQueryString = routePart.IndexOf("?", StringComparison.InvariantCulture);
            routePart = requestUrl.Substring(0, indexQueryString);
            queryStringPart = requestUrl.Substring(indexQueryString + 1, requestUrl.Length - indexQueryString-1);
            NameValueCollection parameters = new NameValueCollection();
            var parametersList = queryStringPart.Split('&');
            foreach (var paramter in parametersList)
            {
                var keyAndvalue = paramter.Split('=');
                parameters.Add(keyAndvalue[0], keyAndvalue[1]);
            }
                
            request.Setup(req => req.Params).Returns(parameters);
        }

        // Setup all Http Context
        request.Setup(req => req.ApplicationPath).Returns(appPath);
        request.Setup(req => req.AppRelativeCurrentExecutionFilePath).Returns(routePart);
        request.Setup(req => req.PathInfo).Returns(string.Empty);
        request.Setup(req => req.ServerVariables).Returns(new NameValueCollection());
        response.Setup(res => res.ApplyAppPathModifier(It.IsAny<string>())).Returns((string virtualPath) => virtualPath);
        user.Setup(usr => usr.Identity).Returns(identity.Object);
        identity.Setup(ident => ident.IsAuthenticated).Returns(true);
        context.Setup(ctx => ctx.Request).Returns(request.Object);
        context.Setup(ctx => ctx.Response).Returns(response.Object);
        context.Setup(ctx => ctx.Session).Returns(session.Object);
        context.Setup(ctx => ctx.Server).Returns(server.Object);
        context.Setup(ctx => ctx.User).Returns(user.Object);

        return context.Object;
    }

    /// <summary>
    /// Class used to return the RouteData and the HttpContextBase
    /// </summary>
    public class RouteAndContext
    {
        public RouteAndContext(HttpContextBase httpContextBase, RouteData routeData)
        {
            this.HttpContext = httpContextBase;
            this.RouteData = routeData;
        }
        public HttpContextBase HttpContext { get; private set; }
        public RouteData RouteData { get; private set; }
    }
}

Indeed this class has hard-coded area class in the TestInitialize method. But, my project contains only few areas and I want to keep everything simple. I will all every area one by one in this method. However, you could make it generic very easily by passing to the constructor of that method a list of AreaRegistrationContext.

The test concerning the Html’s helper is also pretty simple once you have this class to inherit from. In you arrange you get the UrlHelper. You could set this initialization inside the method that run between each test, but this one allow to pass the application path. This parameter allows to not use the domain only has the base application path. The acting section of this unit test is the same as what is using when you are using the Html helper to generate an Url.

[TestMethod]
public void ControllerUserContest_ActionEnter()
{
    // Arrange
    UrlHelper helper = base.GetUrlHelper();
    var routeParameters = new RouteValueDictionary(new Dictionary<string, object>()) {
                                        {Constants.AREA, Constants.Areas.CONTEST},
                                        {Constants.RoutePortionName.ACTIVE_CURRENT_CONTEST_ID,1}
            };

    // Act
    string url = helper.Action("Enter", "UserContest", routeParameters);

    // Assert
    Assert.AreEqual("/" + Constants.Areas.CONTEST + "/1/Enter", url);
}

The helper.Action calls the url helper Action method and this is why we are using this one to get the string Url to test.

public virtual TagBuilder GenerateActionLink(
            [NotNull] string linkText,
            string actionName,
            string controllerName,
            string protocol,
            string hostname,
            string fragment,
            object routeValues,
            object htmlAttributes)
        {
            var url = _urlHelper.Action(actionName, controllerName, routeValues, protocol, hostname, fragment);
            return GenerateLink(linkText, url, htmlAttributes);
        }

The code above is from Asp.Net MVC framework which shows what the GenerateActionLink is using the url helper Action method. So, as you can see, once you have the inherit base class, it is a matter of a single calls and some assertion to test all your routes. I strongly suggest that for each of your routes you have a single unit test to avoid any huge impact on your website.

1000 Unit Tests

I have this side project that I am burning a lot of time since about 1 year now. It reaches few days ago the milestone of 1000 automated unit tests.

TestExplorerReach1000UnitTests

The code coverage is not bad too. I stroked the test projects because they are not significant. The model is cover at 82% which contains the core business logics. The service layer contains some integration logic and should be more covered but well we still have a coverage that make me comfortable and this is what is important so far. I am also proud of the 69% of the data access. Some of these database tests mock the database and some not which is perfect to test if Entity Framework is not breaking. The main difference is that with those 1000 unit tests I feel that I’ll be able to continue to add features without disturbing parts that I wouldn’t expect to broke. This was one of the main reason of that project — to rebuild the old one that had less than 100 unit tests in PHP on a period of 10 years!

Coverage1000Tests

I am also using nDepend software to keep track of the unit tests. That tool is great for identifying some part to improve your software but it is also great to track your tests coverage during the life of your software.

nDependCodeCoverage

As you can see, we can track in time the number of lines, number of comments and the coverage. We can see two spikes down which were caused from a batch of tests that was failing during major refactoring. The graph show that I am pretty constant in the amount of code that I wrote every months. I am also keeping the same trend with the coverage. The number of comments is slightly going down but this is something I knew and will fix soon.

The project should be mostly done by the end of the year. Their is a big chance to reach 1500 units tests. I also plan to integrate some function tests with Visual Studio Coded UI for main scenario. So far, having these tests are more of a blessing than anything. Not only they will be really important later but even when writing them these make me think twice about how easy to make them to test and also revise the code in a rapid way which remove a lot of errors to go into production.

Unit Testing IDbSet with InMemoryDbSet

Unit testing code near of your data access layer is not always easy. However, if you work design pattern like Unit of work or have at least regrouped your unit of DbSet in a centralized place, your unit tests can be not too hard to test. This is quite easy in fact if you are returning the IDbSet than you are in lock because you can Mock the DbSet and even use a nice Nuget’s package called FakeDbSet which has a InMemoryDbSet.

You can install in your unit of test the FakeDbSet with this Nuget’s command.

Install-Package FakeDbSet

Here is a real example of a unit test that is intended to verify that when we call the repository that we get specific entity. The repository has in fact a filter — Entity Framework where clause — that return only stock that is with the status Waiting. This test verify that the Linq to Entity is really filtering correctly. The stockOrderSet is the fake.

//Configuration in the constructor of the test machine
this.stockOrderSet = new InMemoryDbSet<StockOrder>(true);
this.UnitOfWork.Setup(d => d.Set<StockOrder>()).Returns(stockOrderSet);
this.realTimeRepository = new RealTimeValuesRepository(base.UnitOfWork.Object);
//...
[TestMethod]
public void GivenStocksSymbolToRefresh_WhenOrderActiveWithStockExpired_ThenGetOneToRefresh()
{
	// Arrange
	this.stockOrderSet.Add(new StockOrder(){StockSymbol = "A", OrderStatus = OrderStatusType.Waiting});
	this.stockOrderSet.Add(new StockOrder(){StockSymbol = "B", OrderStatus = OrderStatusType.Executed});

	// Act
	var stocks = realTimeRepository.GetStocksSymbolToRefresh();

	// Assert
	Assert.AreEqual(1, stocks.Count());
	Assert.AreEqual("A", stocks.First());
}

The initialization of the fake DbSet is set by specifying that we do not want to retain any value set between tests. The Linq is executed as it would with a DbSet connected to entity framework. As you can see, I am using a mocking framework to specify that every time the unit of work class’s DbSet for the StockOrder is used to use the fake DbSet. You can do the same if your repository has directly the the DbSet but these would require to be virtual to mock them. Everything is easy testable because of different pattern. Because we are injecting the unit of work (which contains the DbSet) into the repository, than it is easy to mock the unit of work to return the fake DbSet.

The code of the FakeDbSet is available on GitHub (https://github.com/a-h/FakeDbSet).