How can I unit test a lock statement?

c#, locking, unit-testing

Solution

The same way you test any other thing: write a test that fails without it. In other words, determine why you are writing the lock in the first place, and write a test that specifies that reason. I assume the reason is thread-safety: if so, write the multi-thread test. If it is some other reason, right that test.

If you really, really want to test calling the lock but not the behavior the lock causes, encapsulate:

public class MyLock : IDisposable
{
    private object _toLock;

    public MyLock(object toLock)
    {
        _toLock = toLock;
        Monitor.Enter(_toLock);
    }

    public virtual void Dispose()
    {
        Monitor.Exit(_toLock);
    }
}

You'll have to make a mockable factory too, of course. Seems like overdoing it to me, but maybe it makes sense in your context.

Problem

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.

Original source

Related problems