1
\$\begingroup\$

I'm doing a hobby game project using Visual Studio 2015 and XNA, via the MonoGame implementation. I wanted to do some unit testing, as I recently discovered this feature in Visual Studio, and want to get a feel for how it can be used.

The problem is, I can't get it to work with the XNA Game object, or anything derived from it.

This is a simple instantiation test I made:

[TestMethod()]
public void MyTest()
{
    try
    {
        MyObject Test = new MyObject();
    }
    catch
    {
        // Fail the test if any exception occurs in the constructor.
        Assert.Fail();
    }
}

Whenever I use my own object in place of MyObject, the test passes. When I use MyGame (derived from Game and with my own properties/methods), the test fails. I've tested the same object in the debugger, and it doesn't throw an exception.

Any idea what I'm doing wrong, or is the Game class just incompatible with Visual Studio unit testing?

\$\endgroup\$
  • \$\begingroup\$ By test failing, do you mean creating a new instance of MyGame causes an exception and the catch then runs Assert.Fail();? \$\endgroup\$ – lozzajp Aug 24 '16 at 8:06
  • \$\begingroup\$ Have you added using your namespace? \$\endgroup\$ – Stefan Agartsson Aug 24 '16 at 11:57
  • \$\begingroup\$ lozzajp, that's correct. When I run the program normally, no such exception occurs. So I'm trying to figure out what it is about the unit test player and Game objects that aren't working together. \$\endgroup\$ – StericHindrance Aug 24 '16 at 23:25
  • \$\begingroup\$ Stefan, yes the test project is using the appropriate namespace. I just checked it to be sure. \$\endgroup\$ – StericHindrance Aug 24 '16 at 23:25
1
\$\begingroup\$

Game class controls lots of things, like a game window and graphics resources. The class has huge (and somewhat time-consuming) global side effects, which make it a bad candidate for unit testing. Unit testing works best when classes under test are isolated and have no global state. I'd practice testing with simpler classes.

In general, I would avoid any references to the Game class in unit tests as much as possible because of the global effects. In some cases, it is unavoidable... but be prepared for hacks and maintenance cost. It is not impossible - some MonoGame unit tests use their own Game class. Relatedly, there have been some (hard-to-debug) issues with game lifecycle and performance.

Without the exception details it's difficult to say for sure, but something (my guess: creating the game window) conflicts with the test runner.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.