问题
This is driving me crazy. I have an extension which we use to alter the Content Response of a request if there is an error. Basically, if everything works it gets serialized to JSON as normal, but if we get an unhandled exception, we serialize based on a different object.
We need unit tests around this but I cannot figure out how to write them. The means to validate that it worked revolves around the StatusCode, the fault Message instance, and the ContentType of the response.
To modify the Response going back, I utilize the WebOperationContext static class. I have seen examples of mocking this, but it seems like I have to hard code special logic that would then begin to percolate into the actual code, which I don't want.
What are some of the best ways to unit test a WCF behavior extension?
回答1:
I had a similar situation, and was unable to mock WCF (at least using Moq), mainly because most classes are either sealed or had internal constructors.
What I did was to have my behavior just apply an IParameterInspector
and an IClientMessageInspector
(in my case I needed both) and put all my logic in either the AfterCall
or BeforeCall
, or whichever one you need, depending on the inspector type.
That way I could test all the logic I cared about. The actual WCF Behavior remained untested, but all it really did was just add the two inspectors and nothing else.
来源:https://stackoverflow.com/questions/10432147/unit-testing-a-wcf-behavior-extension