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:

   1: Isolate.WhenCalled(() =>

   2:     WebOperationContext.Current.IncomingRequest.UserAgent)

   3:     .WillReturn("MyAgent");

   4:  

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

   1: using (var wcf = new WebChannelFactory<MyServer>(new Uri(baseAddress)))

   2: {

   3:     MyServer channel = wcf.CreateChannel();

   4:     var stream = channel.GetData(10, 10);               

   5: }

   6:  

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: var fakeContext = Isolate.Fake.Instance<WebOperationContext>(Members.CallOriginal, ConstructorWillBe.Ignored);

   2: Isolate.WhenCalled(() => fakeCurrent.IncomingRequest.UserAgent).WillReturn("MyAgent");

   3: Isolate.Swap.NextInstance<WebOperationContext>().With(fakeContext);

  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

  • Christian Wirth

    Hehe! Nice Trick!

  • Kei

    I don’t see the solution?

TOP