Easy way to mock a WCF service?

前端 未结 3 430
清歌不尽
清歌不尽 2020-12-28 23:54

I\'ve got an app which is using a WCF service. Now I\'d like to add unit tests to the app.

For some cases I need to mock the WCF service, since getting the desired b

3条回答
  •  囚心锁ツ
    2020-12-29 00:31

    You can you Moq mocking framework. Based on the example that you have provided:

    ChannelFactory channelFactory = new ChannelFactory("");
    IMyWcfService proxy = channelFactory.CreateChannel();
    proxy.CallMyStuff();
    proxy.Close();
    

    Here is how a mocking implementation will look like:

    Mock channelMock = new Mock(MockBehavior.Strict);
    channelMock
        .Setup(c => c.CallMyStuff())
        .Returns("");
    
    string myStuff = channelMock.Object.CallMyStuff();
    

    After you have added a proxy for the WCF service - you should have a channel interface available to you, called IMyWcfServiceChannel.

    Depending on the return type of service method you are calling - you can set just about any output. In the example above I used string type as an example.

    In order to use the above solution more efficiently you might want to create 2 constructors for the business layer like so:

    public class Example1
    {
        IMyWcfServiceChannel _client;
    
        public Example1()
        {
            var factory = new ChannelFactory("binding");
            _client = factory.CreateChannel();
        }
    
        public Example1(IMyWcfServiceChannel client)
        {
            _client = client;
        }
    
        public string CallMyStuff()
        {
            return _client.CallMyStuff();
        }
    }
    

    So on the prod you use parameter-less constructor. In unit tests you use parameter-full constructor and pass mock to it (channelMock.Object).

提交回复
热议问题