views:

165

answers:

1

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

+1  A: 

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.

Elisha
ok good idea..and how can i get a reference to this thread???i'm testing a code that encapsulate this stuff..
Chen Kinnrot
The "recipe" is to design it for testability, it requires some work. You can make the callback/thread/worker visible to the test (using InternalsVisibleTo or by making it virtual and test it on an inherited class). You can take a look at an example: http://stackoverflow.com/questions/1770830/c-how-to-test-a-basic-threaded-worker-class/1770886#1770886.Other option, which I like less, is to add some "buffer" by putting the test thread to sleep before the Assert call.
Elisha