单元测试servicestack服务,自定义序列化/反序列化 [英] Unit testing servicestack services with custom serialization / deserialization

查看:178
本文介绍了单元测试servicestack服务,自定义序列化/反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有了提供了自己的德/序列化机制的一个问题测试Web服务。

I have a problem testing webservice that has its own de/serialization mechanism provided.

我的样本工作正在使用由 TaskService 类:

My sample Task class that is being used by TaskService:

public class Task
{
    public string TaskName { get; set; }
    public string AuxData { get; set; }

    public static void RegisterCustomSerialization(IAppHost appHost)
    {
        appHost.ContentTypeFilters.Register("application/xml", SerializeTaskToStream, DeserializeTaskFromStream);
    }

    public static void SerializeTaskToStream(IRequestContext requestContext, object response, Stream stream)
    {
        var tasks = response as List<Task>;
        if (tasks != null)
        {
            using (var sw = new StreamWriter(stream))
            {
                if (tasks.Count == 0)
                {
                    sw.WriteLine("<Tasks/>");
                    return;
                }

                sw.WriteLine("<Tasks>");
                foreach (Task task in tasks)
                {
                    if (task != null)
                    {
                        sw.WriteLine("  <Task type=\"new serializer\">");
                        sw.Write("    <TaskName>");
                        sw.Write(task.TaskName);
                        sw.WriteLine("</TaskName>");
                        sw.Write("    <AuxData>");
                        sw.Write(task.AuxData);
                        sw.WriteLine("</AuxData>");
                        sw.WriteLine("  </Task>");
                    }
                }
                sw.WriteLine("</Tasks>");
            }
        }
        else
        {
            var task = response as Task;
            using (var sw = new StreamWriter(stream))
            {
                if (task != null)
                {
                    sw.WriteLine("  <Task type=\"new serializer\">");
                    sw.Write("    <TaskName>");
                    sw.Write(task.TaskName);
                    sw.WriteLine("</TaskName>");
                    sw.Write("    <AuxData>");
                    sw.Write(task.AuxData);
                    sw.WriteLine("</AuxData>");
                    sw.WriteLine("  </Task>");
                }
            }
        }
    }

    public static object DeserializeTaskFromStream(Type type, Stream stream)
    {
        if (stream == null || stream.Length == 0)
            return null; // should throw exception?
        XDocument xdoc = XDocument.Load(stream);
        XElement auxData = xdoc.Root.Element("AuxData");

        return new Task() { AuxData = auxData.Value };
    }


    public override bool Equals(object obj)
    {
        Task task = obj as Task;
        if (task == null)
            return false;
        return TaskName.Equals(task.TaskName);
    }

    public override int GetHashCode()
    {
        return TaskName.GetHashCode();
    }
}

我根据我的序列化/反序列化的代码上:< A HREF =http://www.servicestack.net/ServiceStack.Northwind/vcard-format.htm相对=nofollow> http://www.servicestack.net/ServiceStack.Northwind/vcard-format.htm 和 HTTPS ://github.com/ServiceStack/ServiceStack.Examples/blob/master/src/ServiceStack.Northwind/ServiceStack.Northwind.ServiceInterface/VCardFormat.cs

I have based my serialization / deserialization code on: http://www.servicestack.net/ServiceStack.Northwind/vcard-format.htm and https://github.com/ServiceStack/ServiceStack.Examples/blob/master/src/ServiceStack.Northwind/ServiceStack.Northwind.ServiceInterface/VCardFormat.cs

我的基本测试类如下:

public class SimpleRestTestBase : AppHostBase
{
    public SimpleRestTestBase() : base( "SimpleRestTestBase", typeof(TaskService).Assembly)
    {
        Instance = null;
        Init();
    }

    public override void Configure(Funq.Container container)
    {
        SetConfig(new EndpointHostConfig
        {
            DefaultContentType = ContentType.Xml
        }
        );

        Task.RegisterCustomSerialization(this);

        Routes
          .Add<Task>("/tasks/{TaskName}")
          .Add<List<Task>>("/tasks");

        container.Register(new List<Task>());
    }
}

和失败的单元测试:

[TestFixture]
public class SimpleTest : SimpleRestTestBase
{
    [Test]
    public void TestMetodRequiringServer()
    {
        var client = (IRestClient)new XmlServiceClient("http://localhost:53967");
        var data = client.Get<List<Task>>("/api/tasks");
    }
}



使用NUnit的测试运行时,我得到的例外是:

The exception I get when using nUnit test runner is:

Testing.SimpleTest.TestMetodRequiringServer:
System.Runtime.Serialization.SerializationException:错误在第1行位置9.期望元素ArrayOfTask 从命名空间http://schemas.datacontract.org/2004/07/ServiceStackMVC'..遇到元素名为'任务',命名空间''。

我如何通过我的自定义序列化/ deseialization代码到 XmlServiceClient

How do I pass information about my custom serialization/deseialization code to the XmlServiceClient?

推荐答案

您要替换通用的XML序列化格式(应用/ XML)与强烈耦合到只能处理1 Web服务输出的定制版本 - 这是很少你想要什么因为它会阻止(即中断)的所有其他服务,从返回XML。
。如果你想返回自定义XML,只是限制为返回一个XML字符串,而不是需要的服务。

You're overriding the generic XML Serialization format (application/xml) with a custom version that is strongly-coupled to only handle 1 web service output - this is very rarely what you want since it will prevent (i.e. break) all your other services from returning XML. If you want to return custom XML, just limit to the services that need it by returning a xml string instead.

您不能改变的实施XmlServiceClient因为它是强耦合到XML序列化/反序列化的ServiceStack使用。您应该使用原始HTTP客户端送你想要的确切XML负载。这里有一个例子发送原始XML与.NET的Web请求:
http://stackoverflow.com/a/8046734/85785

You can't change the implementation of XmlServiceClient as it is strongly coupled to the XML Serialization/DeSerialization that ServiceStack uses. You should use a raw HTTP Client to send the exact XML payload you want. Here's an example sending raw XML with .NET's web request: http://stackoverflow.com/a/8046734/85785

既然你回来和发送自定义XML,你可能还需要重写自定义请求粘结剂为Web服务让您有机会反序列化的要求

Since you're returning and sending custom XML you may also want to override the Custom Request Binder for your web service so you have an opportunity to deserialize the request how you want.

有关如何做到这一点的一些示例,请参见下面的wiki页面HREF =https://github.com/ServiceStack/ServiceStack/wiki/Serialization-deserialization相对=nofollow> https://github.com/ServiceStack/ServiceStack/wiki/Serialization-deserialization

https://github.com/ServiceStack/ServiceStack/wiki/Serialization-deserialization

请注意:返回的自定义XML是不是因为它的理想被绕过许多ServiceStack的强类型化,智能化和固执己见的自然优势。

Note: returning custom XML is not ideal since it by-passes many of the advantages of ServiceStack's strong-typed, intelligent and opinionated nature.

这篇关于单元测试servicestack服务,自定义序列化/反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆