[英]How to mock OperationContext.Current (WCF Message)
Currently I have a challenge to unit test a production code. 目前,对单元测试生产代码存在挑战。 We have a function to retrieve an IP address from an incoming WCF messages.
我们具有从传入的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;
}
The question is, what should I do so that I could test the checking of the IP in the DoSomething()
? 问题是,我应该怎么做才能在
DoSomething()
测试IP的检查?
[Test]
Public void DoSomethingTest()
{
//Arrange...
// Mock OperationContext so that we can manipulate the ip address in the message
// Assert.
...
}
Should I change the way I use the Operation context in a way so that I can mock it(eg implement an interface and mock the implementation of the interface)? 我是否应该以一种可以模拟它的方式(例如,实现一个接口并模拟该接口的实现)来更改使用Operation上下文的方式?
I would wrap the call with a static helper: 我将用一个静态助手包装该呼叫:
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;
}
}
Then in GetIpFromWcfMessage
I would call: 然后在
GetIpFromWcfMessage
我将调用:
private string GetIpFromWcfMessage()
{
var props = MessagePropertiesHelper.Current;
string ip = ...//use the IP from MessageProperties to extract the ip
return ip;
}
And I would be able to switch the implementation in the test scenario: 我将能够在测试场景中切换实现:
[Test]
Public void DoSomethingTest()
{
//Arrange...
// Mock MessageProperties so that we can manipulate the ip address in the message
MessagePropertiesHelper.SwitchCurrent(() => new MessageProperties());
// Assert.
...
}
Here you can find my answer to similar problem: https://stackoverflow.com/a/27159831/2131067 . 在这里您可以找到我对类似问题的答案: https : //stackoverflow.com/a/27159831/2131067 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.