WCF单元测试

     本示例使用的单元测试工具为VS2010自带的单元测试工具,Mock工具为WCFMock:使用及下载地址为:http://wcfmock.codeplex.com/

     WCFMock主要提供两个DLL,WCFMock和Moq,均可下载获得
    

    WCF服务端:
        需要引入:WCFMock.dll
        在提供服务接口的类开头添加(用于mock WebOperationContext ):using WebOperationContext = System.ServiceModel.Web.MockedWebOperationContext;

     测试项目:(更多使用方式可参考WCFMock项目)
        

[TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            string requestXml = "请求数据";

            Mock<IWebOperationContext> mockContext = new Mock<IWebOperationContext> { DefaultValue = DefaultValue.Mock };
          
            string ret = string.Empty;
            using (new MockedWebOperationContext(mockContext.Object))
            {
                //调用服务器端接口方法
                ReportService sampleService = new ReportService();
                ParseUtil pu = new ParseUtil();
                Stream s = sampleService.LoginPost(string.Empty, pu.StringToStream(loginXml));
                ret = pu.StreamToString(s); //接口返回数据
            }

            //Mock返回类型,否则服务器端调用WebOperationContext.Current.OutgoingResponse.ContentType是回报null异常
            mockContext.VerifySet(c => c.OutgoingResponse.ContentType, "text/xml");

            string retXml = "预期的数据";

            Assert.AreEqual(retXml, ret);
        }
    }

原文地址:https://www.cnblogs.com/gossip/p/2469561.html