outcoldman Denis Gladkikh

How to use Moq and nUnit to write Unit Tests for Windows Runtime libraries

TDD, nUnit, Moq, Windows Runtime, WinRT, .NET Core, and Unit Tests

I love to use Moq library, it is the best mocking framework for me. Visual Studio provides Fakes framework, but my opinion is that it is for slightly different issues. Fakes is a framework for making fakes, not mokes. For example if you need to change how System.IO.File.Exist handles the path or if for some reason you need to change return value of System.DateTime.Now to test something related to time – this is good job for Fakes framework. If you need to make a Stubs or Mocks I prefer to use Moq, it is just simpler. And don't forget that they work together really well.

The problem which I met when I started to write gMusic is that Moq does not exist for Windows Store Apps (WinRT). It is because "winrt doesn't allow dynamic codegen". But I found a workaround. Instead of creating new Unit Test Class Library for Windows Store Apps I created simple Class Library with Target Framework 4.5 (I will call it Unit Test library). After this I added reference to Windows Runtime using this blog post Referencing the Windows Runtime from Desktop Apps. And the latest point is to include my code from Windows Store Apps library to this Unit Test library. I cannot reference it, because my libraries have different runtimes: Windows Store Apps library has runtime .NETCore (or WinRT, or Windows Runtime, so many names for this). And my Unit Test library has runtime .NETFramework 4.5. Visual Studio does not allow you to mix runtimes, except if they are Portable Libraries. The solution for this is to just include all my code which I want to test from Windows Store Apps library to Unit Test library as links to files Adding an Existing Item as a Link (you can just use drag'n'drop in Solution Explorer with pressed Shift+Ctrl to move some folder or files from one project to another and make it as links).

It is not a perfect solution, but works for me.

Have feedback or questions? Looking for consultation?

My expertise: MongoDB, ElasticSearch, Splunk, and other databases. Docker, Kubernetes. Logging, Metrics. Performance, memory leaks.

Send me an email to public@denis.gladkikh.email.

The content on this site represents my own personal opinions and thoughts at the time of posting.

Content licensed under the Creative Commons CC BY 4.0.