Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top