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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With