【问题标题】:How to mock OperationContext.Current (WCF Message)如何模拟 OperationContext.Current(WCF 消息)
【发布时间】:2014-11-26 11:29:59
【问题描述】:

目前我面临对生产代码进行单元测试的挑战。我们有一个函数可以从传入的 WCF 消息中检索 IP 地址。

public void DoSomething(){
    var ipAddressFromMessage = GetIpFromWcfMessage();

    var IpAddress = IPAddress.Parse(ipAddressFromMessage);

    if(IpAddress.IsLoopback)
    {
        // do something 
    }
    else
    {
        // do something else
    }
}

private string GetIpFromWcfMessage()
{       
    OperationContext context = OperationContext.Current;
    string ip = ...//use the IP from context.IncomingMessageProperties to extract the ip

    return ip;    
}

问题是,我应该怎么做才能测试DoSomething()中的IP检查?

[Test]
Public void DoSomethingTest()
{
    //Arrange...
    // Mock OperationContext so that we can manipulate the ip address in the message

    // Assert.
    ...
}

我是否应该改变我使用 Operation 上下文的方式,以便我可以模拟它(例如,实现一个接口并模拟该接口的实现)?

【问题讨论】:

    标签: c# wcf unit-testing mocking rhino-mocks


    【解决方案1】:

    我会用静态助手来包装调用:

    public static class MessagePropertiesHelper
    {
      private static Func<MessageProperties> _current = () => OperationContext.Current.IncomingMessageProperties;
    
    
      public static MessageProperties Current
      {
          get { return _current(); }
      }
    
      public static void SwitchCurrent(Func<MessageProperties> messageProperties)
      {
          _current = messageProperties;
      }
    
    }
    

    然后在GetIpFromWcfMessage我会打电话:

    private string GetIpFromWcfMessage()
    {       
        var props = MessagePropertiesHelper.Current;
        string ip = ...//use the IP from MessageProperties to extract the ip
    
        return ip;    
    }
    

    而且我可以在测试场景中切换实现:

    [Test]
    Public void DoSomethingTest()
    {
        //Arrange...
        // Mock MessageProperties so that we can manipulate the ip address in the message    
        MessagePropertiesHelper.SwitchCurrent(() => new MessageProperties());
    
        // Assert.
        ...
    }
    

    在这里你可以找到我对类似问题的回答:https://stackoverflow.com/a/27159831/2131067

    【讨论】:

    • 作为对问题的评论会更好。由于该网站希望“站稳脚跟”,因此在 stackoverflow 上不赞成“仅链接答案”。当然,链接到 SO 本身仍然允许这样做,但“低质量答案”猎人可能会标记这一点。
    • 感谢您的提示,我编辑了答案。现在它有一个基于问题的示例,并额外指向类似的答案。
    猜你喜欢
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 2018-01-04
    • 2014-12-22
    • 2011-05-02
    相关资源
    最近更新 更多