WCF tip – How to fake a method inside WebOperationContext

One of our customers had a very interesting problem. When using he needed to set WCF’s WebOperationContext.Current.IncomingRequest.UserAgent to return a specific string.

Usually this would not have been a problem using the AAA API:

Later in the code a new channel was created using WebChannelFactory: 

And then something strange happened – the test failed because WCF has thrown a NullReferenceException from code that seemed to have absolutely nothing to do with the simple behavior we’ve set.

It seemed that when we’ve set behavior we’ve also accidentally set WebOPerationContext.Currect to always return a fake object. later on WCF framework tried to set or get some value from the current context and received null instead.

This seemed to be a tricky problem – how do we set the return value on UserAgent without faking the current context while doing so?

This can be done by replacing Isolate.WhenCalled with the following lines:

  1. Create a fake WebOperationContext that will call its original methods but not call its constructor
  2. Set the desired behavior – return “MyAgent”
  3. Tell Isolator to swap the next instance created with the fake context

What we did is to provide WCF with a “mostly working” WebOperationContext he can use while still setting the desired method to return the value we need for out test to pass