Click here to Skip to main content
15,891,828 members
Articles / Programming Languages / C#
Technical Blog

Unit test WCF with serialization

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
19 Jul 2013CPOL 6.4K   1  
Unit test WCF with serialization.

When unit-testing WCF interfaces we can simply instantiate classes that implement them and call them directly. However in real life DTOs are serialized and transferred via the network before hitting the method. Return value is serialized/deserialized in the same way. Because of serialization, scenarios that work in tests may fail in real life.

The following is a simple helper class that creates proxy which serializes arguments and return values using WCF serializer. The code depends on Unity and Unity.Interception.

This is the code helper:

C#
public static class WcfTestProxy
{
    public static T Build<T>(T obj, Type[] knownTypes) where T: class
    {
        return Intercept.ThroughProxy<T>(obj, new InterfaceInterceptor(),
                                         new IInterceptionBehavior[]
                                             {
                                                 new EnterProxyBehaviour(knownTypes),
                                                 new ExitProxyBehaviour(knownTypes)
                                             });
    }
}

Entry behaviour serializes arguments:

C#
internal class EnterProxyBehaviour : IInterceptionBehavior
{
    public IMethodReturn Invoke(IMethodInvocation input, 
           GetNextInterceptionBehaviorDelegate getNext)
    {
        for (int i = 0; i < input.Inputs.Count; i++)
        {
            input.Inputs[i] = SerDeser(input.Inputs[i]);
        }

        var methodReturn = getNext().Invoke(input, getNext);
        return methodReturn;
    }
}

Exit behaviour serializes the return value:

C#
internal class ExitProxyBehaviour : IInterceptionBehavior
{
    public IMethodReturn Invoke(IMethodInvocation input, 
           GetNextInterceptionBehaviorDelegate getNext)
    {
        var methodReturn = getNext().Invoke(input, getNext);
        methodReturn.ReturnValue = SerDeser(methodReturn.ReturnValue);
        return methodReturn;
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --