Alex Rivera | Logout

How can I unit test a lock statement?

Asked 2012-05-30T13:07:20.580
11

How would I write a unit test to ensure that a lock was acquired?

For example:

public void AddItem(object item)
{
    lock (_list)
    {
        _list.Add(item)
    }
}

Is there a way to ensure that the lock statement is run?

Edit: I'm not trying to prove thread-safety (this I would assume), just that the lock() statement is called.

For example, I might test a new object() statement by substituting it in a CreateObject() factory function.

Edit
Report

1 Answer

0

You need a small program where you emulate the reading and writing with threads...

In a new thread create 10,000 items and add them, while in another thread reading and then sleeping for some time.

Then in the main wait for both threads to exit and you should have the results according to the amount of times the test called add and did not call remove...

E.g when i % 2 == 0 then remove instead of add in the producer threads... this should also effect the consumer thread...

see How to wait for thread to finish with .NET?

answered 2012-05-30T13:21:44.707

Your Answer