Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing Parallel.Foreach C#

I have been using JustMock for unit testing in C#. The problem I am facing is I cannot assert the functions called inside Parallel.Foreach. However the assignments done inside can be asserted.

Parallel.ForEach(aList, entity =>
{
    //Can be asserted using  Assert(5,parameter.value) in the test
    parameter.value = 5;

    //Cannot be asserted, assertion fails Mock.Assert(parameter) in the test
    //is arranged using MustBeCalled
    parameter.call();   
})

I found the same issue in other test cases also. Is this some wrong behavior of JustMock?

like image 935
Sunny Avatar asked Aug 26 '16 10:08

Sunny


People also ask

How do you test for parallel ForEach?

try removing Parallel and just do a normal foreach. Technically, you should lock variables defined outside of the Parallel loop if you intend on modify it from within the Parallel loop. This ensures thread syncing. You may be able see this if you change 5 to be the results of some random number generator.

Does ForEach work in parallel?

ForEach loop works like a Parallel. For loop. The loop partitions the source collection and schedules the work on multiple threads based on the system environment. The more processors on the system, the faster the parallel method runs.


1 Answers

When doing parallel processing you cannot easily assume that something will or will not happen, that's what makes it harder. Instead, you concentrate on signs that will tell you that something is working. The issue here is that Parallel.ForEach stops processing as soon as exception is spotted, while you were expecting it to process all items. Nothing is wrong with your JustMock. Using normal foreach should resolve this issue. if you have reason to use Parallel.Foreach anyway, try to catch all Exception fires here.

like image 112
Md. Tazbir Ur Rahman Bhuiyan Avatar answered Sep 20 '22 12:09

Md. Tazbir Ur Rahman Bhuiyan