使用 nMoq,人们会对给定事件有何期望?

发布于 2024-09-10 22:18:22 字数 359 浏览 12 评论 0原文

假设我想做一个单元测试,我有这个俄罗斯方块游戏,我想开始游戏,什么都不做,然后等待游戏结束(这是为了获得 GameOver 事件):

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

我应该如何制作测试?这可能应该很容易,但我不知道该怎么做。 我唯一的想法是以下形式:

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

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空‖城人不在 2024-09-17 22:18:23

假设 tetris.Start() 是同步的,您可以使用事件处理程序向测试发出信号:

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

如果调用是异步的,您必须同步调用才能到达 < em>在测试上下文中断言

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.

感性不性感 2024-09-17 22:18:23

我写了一个我喜欢使用的小助手类。您可以在此处找到 此处为该类的单元测试。您可以随意使用它,但请自行承担使用风险。我正在使用它进行测试,但很可能存在错误。对于您的情况,使用该类将如下所示:

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

编辑:看起来它还需要 EmitHelpers

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文