WCF Tip – How to unit test an ErrorProvider

A while ago this problem was brought to my attention by one of our customers:

WCF enable us to add a custom error handler as part of the service implementation:


The implementation of ErrorHandler is pretty straight forward:


Writing a unit test for the error handling code seems easy (using Isolator) just call Fault and check if the logger’s WriteException method was called:


Unfortunately this simple test does not work or more accurately it works only some of times and failed at others.

Debugging the code will show that when the test failed it was because HandleError method executes after the test ended, in fact the method is invoked asynchronously by WCF. It seems that because the method run on a different thread there is no grantee that it will be called before our test ends.

There is a way to make sure that the test won’t end until HandleError is called using simple thread synchronization.


This solution is not perfect – the test could fail if the timeout is reached before the error handler is called, this can be solved by using a big enough (but not too big) timeout should solve this issue while preventing the test run to halt in case of failing test.

  • Morgado

    You can always terminate the test as inconclusive if the WaitOne exits by timeout.

  • Eli Lopian

    Great Post,
    I would not use the [ExpectedException] but used the following pattern:

    Assert.Fail("Should have throw");
    } catch (FaultException e)

    Makes me wonder why we don't have an api for this.