Telerik® JustMock™ by Progress

Threadpool mocking is one of the advanced features supported in Telerik JustMock. It allows you to access mocked objects inside another thread and work with them as expected.

Note

This feature is available only in the commercial version of Telerik JustMock.

Refer to this topic to learn more about the differences between both the commercial and free versions of Telerik JustMock.

Mocking inside a thread

We will use the following sample code to illustrate how you can do this.

C# Copy imageCopy
public class Mockable
{
    public bool IsMocked
    {
        get
        {
            throw new NotImplementedException();
        }
    }
}

internal class WaitLatch : IDisposable
{
    public void Wait()
    {
        while (autoResetEvent.WaitOne())
        {
            if (currentCount >= initialCount)
                break;
        }
    }

    public void Signal()
    {
        Interlocked.Increment(ref currentCount);
        autoResetEvent.Set();
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
            if (autoResetEvent != null)
            {
                autoResetEvent = null;
            }
    }

    ~WaitLatch()
    {
        Dispose(false);
    }

    private int currentCount;
    private const int initialCount = 1;

    AutoResetEvent autoResetEvent = new AutoResetEvent(false);
}
 	

Here the WaitLatch class represents the thread we are going to execute. Inside the thread we will access an instance of the Mockable class. Let's see a complete example:

C# Copy imageCopy
[TestMethod]
public void ShouldInvokeMockInsideAChildThreadFromThreadPool()
{
    var mockable = Mock.Create<Mockable>();
    Mock.Arrange(() => mockable.IsMocked).Returns(true);

    bool mocked = false;

    var latch = new WaitLatch();

    ThreadPool.QueueUserWorkItem((cookie) =>
    {
        try
        {
            mocked = mockable.IsMocked;
        }
        finally
        {
            latch.Signal();
        }
    });

    latch.Wait();

    Assert.IsTrue(mocked);
}

Here we use Mock.Arrange to say that the IsMocked property should return true. Then we create another thread using ThreadPool.QueueUserWorkItem and access the mocked object. Finally we assert that the expected value is returned.

Note

Static member mocking and future mocking does not work across threads by default. To make a static or future arrangement valid across all threads, add the .OnAllThreads() clause to the arrangement, e.g.

CopyC#
Mock.Arrange(() => DateTime.Now).Returns(new DateTime()).OnAllThreads();

See Also