簡體   English   中英

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

[英]How to mock OperationContext.Current (WCF Message)

目前,對單元測試生產代碼存在挑戰。 我們具有從傳入的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上下文的方式?

我將用一個靜態助手包裝該呼叫:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM