How to Use Moq With .NET Core Apps

Writing automatic tests is crucial if you care about producing code with good quality. And why shouldn’t you! Yes, writing tests takes time, but the effort will soon be repaid. At least if the code is going to be around for a while. Have you ever been in a project where no one dares to refactor code since it is without coverage? Come on, be a Software Professional!

Enough said about that…

When I test my code I make use of a suite of tools to make the work as easy as possible. There are many tools out there, and at least I am not interested in learning to use more of them than I have to. All devs have their favorite tools for testing, and one of mine is Moq. When a new framework or platform is released I would very much still be able to instrument the mocking framework the way I am used to.

If you try to use Moq through the official NuGet feed in an ASP.NET Core- or Universal Windows Platform (UWP) project you will find yourself in trouble. Some of the error messages you might see are:

  • The dependency Moq 4.2.1510.2205 in project MyWebApplication does not support framework DNXCore,Version=v5.0
  • Moq 4.2.1510.2205 is not compatible with UAP,Version=v10.0.

Moq does simply not support .NET Core yet. Now, what to do?

The ASP .NET Devs at Microsoft to the Rescue

I have come across a fork of the Moq project which luckily has added support for .NET Core. What is even better, there is a public NuGet feed at https://www.myget.org/F/aspnetcidev/api/v3/index.json where packages from that project are available.

One way to use a nonstandard NuGet package source is to create a NuGet.Config-file in the root of your solution folder looking something like this:

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
...
<add key="AspNetVNext" value="https://www.myget.org/F/aspnetcidev/api/v3/index.json" />
...
</packageSources>
</configuration>

Or you can add the AspNetVNext source-tag in your user profile NuGet file at %AppData%\NuGet\NuGet.Config.

Note that the Moq package with .NET Core support is in preview. To reference it, add "moq.netcore": "4.4.0-beta8" as a dependency in your project.json-file.

Thank you Microsoft Devs for allowing me to use Moq on the .NET Core framework!

xUnit and the Universal Windows Platform

Another tool which I’m fond of is xUnit. To get xUnit to work with UWP you have to add it to a Unit Test App project. Adding it to a class library the way you might be used to does not work. The procedure is described in detail in the xUnit documentation.