1

I'm new to XNA game development and I have just started to write a small 3D game. I have written several unit tests to test my code but I have run into a problem. When I want to unit test modules that need to access a Model I haven't found a way to create a ContentManager with which to load Models. In a proper Game, the ContentManager is provided by the framework. In my unit tests, I would have to create it myself but I have no idea how to do this.

An alternative to load Models using a ContentManager would be to create Model objects programatically but that seems rather tedious. Another alternative would be to mock the Models using, for example Moq but that seems equally tedious.

Have anyone else encountered this problem and solved it?

David Nordvall
  • 12,404
  • 6
  • 32
  • 52

2 Answers2

2

Unit testing an XNA project is a common issue and one that is often discussed. Usually, the problem is due to either needing access to an instance of either Game, GraphicsDevice, or (in your case) ContentManager, and there not being any easy way of obtaining one.

You can see related discussions here, here, and here.

I believe the generally accepted practice is to re-evaluate what you are trying to test to see if you actually need these references, or if you can find a way around them.

Failing that, could your test case be sufficiently covered by playtesting?

If neither of the above apply, mocking the objects can prove to be rather difficult due to the requirements placed on them by their parent classes/interfaces, but I have heard of people doing it. I have also heard it is possible to actually create a GraphicsDevice using an invisible form, but I have not done this myself.

For my own tests, I've gone with not testing any graphical elements (Drawing, Resource Loading, etc.). It does leave a bit of a hole in my code coverage, but after spending a few days searching for ways of solving this exact problem, and not finding any answers, I decided testing my library functions (which do the majority of the work in my projects anyway) was good enough.

Community
  • 1
  • 1
Shaun Hamman
  • 2,287
  • 4
  • 21
  • 33
0

The code in this answer explains how to create a stand-alone instance of ContentManager.

Community
  • 1
  • 1
Andrew Russell
  • 26,924
  • 7
  • 58
  • 104