开发者

Using nMoq, how would one expect for a given Event?

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜