views:

45

answers:

2

Let's say I want to make a Unit-Test where I have this Tetris game and I want to start the game, do nothing, and wait for the game to be over (this is, to get a GameOver event):

Tetris tetris = new Tetris();
tetris.GameOver += something;
tetris.Start();

How should I make the test? This should probably be easy but I can't see how to do it. My only idea would be something of the form:

Tetris tetris = new Tetris();
tetris.GameOver += delegate() { Assert.True(); };
tetris.Start();

Thanks

+1  A: 

Assuming tetris.Start() is synchronous you can signal to the test using the event handler:

Tetris tetris = new Tetris();
bool wasRaised = false;
tetris.GameOver += delegate() { wasRaised = true; };
tetris.Start();
Assert.IsTrue(wasRaised);

If the call is asynchronous you must synchronize the call in order to get to the Assert in the test context.

Elisha
+1  A: 

I wrote a little helper class that I like to use. You can find the class here and the unit tests for the class here. You can feel free to use it, but please use at your own risk. I'm using it for my tests, but it's quite possible there are bugs. For your case, using the class would look like this:

        Tetris tetris = new Tetris();
        using (EventAssertion.Raised(tetris, "GameOver").OnlyOnce().Go())
        {
            tetris.Start();
        }

EDIT: Looks like it also requires EmitHelpers.

Dan Bryant