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

时间:2014-11-26 11:30:00

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

目前,我对单元测试生产代码提出了挑战。我们有一个函数从传入的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上下文的方式,以便我可以模拟它(例如实现接口并模拟接口的实现)?

1 个答案:

答案 0 :(得分:5)

我会使用静态帮助器包装调用:

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