Domanda

I was creating a MonoGame project and wanted to create Unit Tests against the existing code. I created a test project and started with a simple test of the GameLopp class (My rename of the Game1.cs class that comes with the project). I created a basic 'setup succeeds' test to make certain than the constructor builds without issue:

    public GameLoopTest()
    {
        using (GameLoop game = new GameLoop())
        { game.Run(); }
    }

    public void Dispose()
    {
        _gameloop = null;
    }

    [Fact]
    public void GameLoop_Setup_Suceeds()
    {
        this.Should().NotBeNull();
    }

Much to my confusion the constructor in the test throws a NullReference Exception. If I step through the test in Debug mode I get a more detailed exception that tells me the GraphicsDeviceManager cannot be found. I searched high and wide but I haven't been able to come up with why the error happens or how it can be resolved.

I don't have a lot of code in that class, but I'd hate to leave something so critical uncovered by unit tests.

È stato utile?

Soluzione

Take a look at the implementation of the Game class in MonoGame.

https://github.com/mono/MonoGame/blob/develop/MonoGame.Framework/Game.cs

In the constructor it creates a GameServiceContainer and then uses it in the GraphicsDevice getter to get an IGraphicsDeviceService.

To make matters more difficult the GraphicsDeviceManager takes a Game class in it's constructor and adds itself as a service to the service container creating a tight coupling between these two classes.

https://github.com/mono/MonoGame/blob/develop/MonoGame.Framework/GraphicsDeviceManager.cs

This is not particularly good design for unit testing but it's not the fault of the MonoGame team because they are just re-implementing the behavior of Microsoft XNA.

I suspect your issue is that your GameLoop class depends on having a valid Game class already constructed which in turn uses the service container internally.

My suggestion is to design your own code so that it can be unit tested and try to decouple it from rendering code in the same spirit you would separate the view from a view model. At best, you might be able to use screenshot tests to confirm that things render correctly if you're really keen.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top