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:
- Create a fake WebOperationContext that will call its original methods but not call its constructor
- Set the desired behavior – return “MyAgent”
- 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