Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing multithreading service methods in mocks

For example I want to test the fact that my multi-threaded method is calling the repository methods n times if I give him n chunks of data from different threads. Of course mocks are not thread safe and even are not supposed to be.

[Test]
public void CanSaveCustomersInParallel()
{
    var customers = new List<List<Customer>>
                        {
                            new List<Customer>
                                {
                                    new Customer {FirstName = "FirstName1"},
                                    new Customer {FirstName = "FirstName2"}
                                },
                            new List<Customer>
                                {
                                    new Customer {FirstName = "FirstName3"},
                                    new Customer {FirstName = "FirstName4"}
                                }
                        };
    _serviceCustomers.ParallelSaveBatch(customers);
    _repoCustomers
        .Verify(x => x.SaveBatch(It.IsAny<List<Customer>>()), Times.Exactly(2));
}

Of course, this test fails sometimes and sometimes it does not. But it is incorrect in its essence. Can you advise me how to re-write it?

like image 346
Yurii Hohan Avatar asked May 05 '26 11:05

Yurii Hohan


1 Answers

Well, the next stub did the trick:

internal class ServiceStub: Service<DummyEntity>
{
    private int _count;

    public int Count
    {
        get { return _count; }
    }

    public override void SaveBatch(IEnumerable<object> entities)
    {
       lock(this)
       {
           _count++;
       }
    }

    public ServiceStub(IRepository<DummyEntity> repository):base(repository)
    {
        _count = 0;
    }
}

And the unit test looks the next way:

    [Test]
    public void CanSaveCustomersInParallel()
    {
        var service = new ServiceStub(new DummyRepository());
        var customers = new List<List<Customer>>
                            {
                                new List<Customer>
                                    {
                                        new Customer {FirstName = "FirstName1"},
                                        new Customer {FirstName = "FirstName2"}
                                    },
                                new List<Customer>
                                    {
                                        new Customer {FirstName = "FirstName3"},
                                        new Customer {FirstName = "FirstName4"}
                                    }
                            };
        service.ParallelSaveBatch(customers);
        Assert.AreEqual(service.Count, customers.Count);
    }
like image 132
Yurii Hohan Avatar answered May 08 '26 01:05

Yurii Hohan