I want to test a game loop that runs forever until the user quits or dies, after that a message is displayed.
Something like this:
[TestFixtureSetUp]
public void SetupMethods()
{
_input = new Mock<IInput>();
_input.SetupProperty(i => i.QuitKey, 'q');
_messenger = new Mock<IMessenger>();
_grid = new Mock<IGrid>();
_clock = new Mock<IClock>();
_game = new Game(_input.Object, _messenger.Object, _grid.Object, _clock.Object);
}
[Test]
public void should_loop_until_player_quits_then_show_confirmation()
{
_input.Setup(g => g.ReadKey()).Returns(_input.Object.QuitKey);
_messenger.Verify(m => m.SendMessage("Are you sure?"));
}
[Test]
public void should_loop_until_player_dies_then_show_game_over_message()
{
_game.IsGameOver = true;
_messenger.Verify(m => m.SendMessage("Game Over"));
}
inside the Game
class I have
public void GameLoop()
{
//gets player input
while (ReadKey() != _input.QuitKey && !IsGameOver)
{
//waits for clock
if (_clock.TimeElapsed % 1000 == 0)
{
//logic
}
}
if (IsGameOver)
{
_messenger.SendMessage("Game Over");
}
else
{
_messenger.SendMessage("Are you sure?");
}
}
to allow the loop to run I found that creating a separate thread for it works, and doesn't hang the test. However when I put the new Thread code in the Setup the tests randomly fail if I do Test All
(I have about 5 or 6). If I do each test separately it's fine.
[SetUp]
public void SetupTest()
{
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
_game.GameLoop();
}).Start();
}
What am I doing wrong?