Wednesday, June 11, 2014

AggregateException in Unit testing Task Parallel Library Asyc Call

Some Background Exception Handling (Task Parallel Library)

If a task is the parent of attached child tasks, or if you are waiting on multiple tasks, then multiple exceptions could be thrown. To propagate all the exceptions back to the calling thread, the Task infrastructure wraps them in an AggregateException instance

http://msdn.microsoft.com/en-us/library/dd997415(v=vs.110).aspx

Problem Statement:

Most of the time when we create a unit testing on Async Method- TPL it executes the unit test completely but ends up throwing AggregateException. This is due to the fact that it completes the one set of flow completely within a thread and comes out without executing all thread in parallel. If you see there is no UI and hence while testing the TPL must understand that unit testing is just to check the conditions of expected output with actual given a input as required whereas TPL works in different context. So ideally we must create test on non TPL methods in such case create separate methods to test on.
http://blog.stephencleary.com/2012/02/async-unit-tests-part-1-wrong-way.html

•An asynchronous method call will either produce a result immediately if one is available and continue execution in the current method or it will produce a result at a later time and immediately return control to the caller of the current method.
•The code that comes after an awaited method – the continuation – is what will be executed when the awaited method returns with a result.
http://www.jayway.com/2012/10/07/asyncawait-in-c-a-disaster-waiting-to-happen/

Workaround:

Brute force method not recommended but can be used if just unit test case conditions with failed and pass data.
[TestClass]
public class TestAsyncClassTest {
    [TestMethod]
    [ExpectedException(typeof(AggregateException))]
    public void SomeAsyncTest() {
    }
}
Post a Comment