首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何模拟OperationContext.Current (WCF消息)

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

Stack Overflow用户
提问于 2014-11-26 19:30:00
回答 1查看 3.5K关注 0票数 2

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

代码语言:javascript
复制
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检查?

代码语言:javascript
复制
[Test]
Public void DoSomethingTest()
{
    //Arrange...
    // Mock OperationContext so that we can manipulate the ip address in the message

    // Assert.
    ...
}

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

EN

回答 1

Stack Overflow用户

发布于 2014-11-27 07:52:05

我会用一个静态帮助器包装这个调用:

代码语言:javascript
复制
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中,我会调用:

代码语言:javascript
复制
private string GetIpFromWcfMessage()
{       
    var props = MessagePropertiesHelper.Current;
    string ip = ...//use the IP from MessageProperties to extract the ip

    return ip;    
}

我将能够在测试场景中切换实现:

代码语言:javascript
复制
[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

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27148023

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档