如何模拟OperationContext.Current(WCF消息)

 rachel_wxh_614 发布于 2022-12-09 15:54

目前,对单元测试生产代码存在挑战。我们具有从传入的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;    
}

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

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

    // Assert.
    ...
}

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

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。

    2022-12-11 03:11 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有