使用 rhino 模拟测试后台工作者

发布于 2024-08-08 15:44:21 字数 174 浏览 2 评论 0原文

假设我在一个类中有一个后台工作者,在后台线程中执行数据库查询。

我想测试这个类,

所以我模拟我的数据库并返回一些集合,到目前为止一切都很好, 确保我的后台工作人员调用了 do work 我想确保结局也发生了。

我注意到测试随机通过和失败(我认为这与线程有关)

任何建议

lets say i have a background worker in a class that perform db query in a background thread.

i wanna test this class

so i mock my db and return some collection so far so good,
make sure my background worker called the do work
and than i wanna make sure that the finish also happened.

I've noticed that the test pass and fail randomly (i think it has something to do with threads)

any suggestions

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

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

发布评论

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

评论(1

本王不退位尔等都是臣 2024-08-15 15:44:21

您可能在后台线程和断言/验证之间存在竞争条件。

例如:

[Test]
public void TestWithRaceCondition()
{
    bool called = false;
    new Thread(() => called = true).Start();
    Assert.IsTrue(called);
}

线程不一定在断言之前结束,有时会,有时不会。这种情况的解决方案是加入后台线程:

[Test]
public void TestWithoutRaceCondition()
{
    bool called = false;
    var thread = new Thread(() => called = true);
    thread.Start();
    thread.Join()
    Assert.IsTrue(called);
}

检查是否存在竞争条件的一种方法是延迟测试线程(在断言之前长时间调用 Thread.Sleep),如果测试停止失败,则这是一个很好的指示竞赛条件。

You may have a race condition between the background thread and the asserts/verifies.

For example:

[Test]
public void TestWithRaceCondition()
{
    bool called = false;
    new Thread(() => called = true).Start();
    Assert.IsTrue(called);
}

The thread doesn't necessarily end before the asserts, sometimes it will and sometimes it won't. A solution to this case is to join the background thread:

[Test]
public void TestWithoutRaceCondition()
{
    bool called = false;
    var thread = new Thread(() => called = true);
    thread.Start();
    thread.Join()
    Assert.IsTrue(called);
}

One way to check if it's a race condition is to delay the test thread (call Thread.Sleep for long time just before the assert) and if the test stops failing that's good indication for race condition.

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