How to use WCFMock w/ DI to mock OperationContext

1.5k views Asked by At

I've been looking at WCFMock to support unit testing of my WCF Services that rely on data in the OperationContext.

If I understand it correctly, my services should receive an instance of IOperationContext which is mapped to an instance of OperationContextWrapper.

OperationContextWrapper has a constructor overload that takes an instance of OperationContext (the constructor to be used for testing), or if none is passed, it defaults to OperationContext.Current (this is the path that will occur during actual production).

I haven't found any examples of Mocking IOperationContext that will allow me to inspect/Add to the IncomingMessageHeaders and OutgoingMessageHeaders collections.

Does someone have an example of this?

I noticed that WCFMock was created back in 2009. Is this still the optimal way of mocking Operation context?

3

There are 3 answers

0
codeMonkey On

I wasn't able to get WCFMock to work properly to mock OperationContext; however I was able to figure out a way to create two ServiceHost's that, when called, create their own contexts, headers, etc. See this answer.

0
Vasil Galinovsky On

Use SetupGet to return needed property value

    var mockContext = new Mock { DefaultValue = DefaultValue.Mock };
    var headers = new MessageHeaders(MessageVersion.Default);
    headers.Add(MessageHeader.CreateHeader("headerName", "Namespace", "value"));
    mockContext.SetupGet(x => x.IncomingMessageHeaders).Returns(() => headers);
    using (new MockedOperationContext(mockContext.Object))
    {
      // test your service
    }
0
Lyon On

I had a similar issue my solution involves using an existing wcfclient and retrieve its innerChannel.

   OperationContext.Current = new OperationContext(new MyWcfClient().InnerChannel);
     OperationContext.Current.OutgoingMessageProperties["MyData"] = "somedata that i needed";

I hope this helps someone