14th March 2017 Olivier

Use SimpleStub as mocking framework for UWP unit testing

I looked lately for UWP mocking framework. You can’t say there are lot of choices. Mainly from the fact that there is no way to dynamically generate classes (as most of the framework mocking frameworks do). Therefore, you have to use another way. Like creating mock classes during the build phase.

I stumbled upon an open source framework, SimpleStubs, maintained by Microsoft Big Park studios (Vancouver). Let’s test it.

Classes to test

We’re going to keep it simple, a service interface and a class that uses it. That simple.

The service interface:

The class to be tested, using the service:

Not super complex, it’s just to show the base. Now let’s install the framework.

Installation

To install, add to the unit test projectNuget theNuget Etg.SimpleStub.

SimpleStubs1

To work around the limitations of UWP dynamic code generation, the framework creates the mocks when building. A limitation prevents him from adding the file that contains the classes automatically to the project, so you must add them yourself.

The file SimpleStubs.generated.cs is located in the directory Properties. To add it, in solution Explorer click on “show all the file”, then click on the file and, via the menu, include it in the project

SimpleStubs2

It must be done once, that is the same file that will be updated when the builds (so no change in it, because it will be overwritten with the next build)

The tests

And finaly, the test:

I verify :

  • That the IsServiceBusy property returns true (just to see if the framework works)
  • The GetCities method returns 2 elements.
  • I put Times.Once in the GetDataAsync of the interface configuration. If the method is called more than once, there is an exception raised. To be sure that it is called only once, I seta Boolean when calling. It is a pity that there is no way to check more simply.

Conclusion

A small friendly framework that will suffice for basic tests. I just found from the verification of the number of calls a little bit hacky…

Have fun!

Mobile and Mixed Reality engineer , Arcana Studio
follow me

Leave a Reply

Your email address will not be published. Required fields are marked *