har*_*s h 2 c# wcf unit-testing rhino-mocks mocking
目前,对单元测试生产代码存在挑战。我们具有从传入的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;
}
Run Code Online (Sandbox Code Playgroud)
问题是,我应该怎么做才能测试IP中的IP检查DoSomething()
?
[Test]
Public void DoSomethingTest()
{
//Arrange...
// Mock OperationContext so that we can manipulate the ip address in the message
// Assert.
...
}
Run Code Online (Sandbox Code Playgroud)
是否应该以一种可以模拟它的方式(例如,实现一个接口并模拟该接口的实现)来更改使用Operation上下文的方式?
小智 6
我将用一个静态助手包装该呼叫:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,GetIpFromWcfMessage
我会打电话给:
private string GetIpFromWcfMessage()
{
var props = MessagePropertiesHelper.Current;
string ip = ...//use the IP from MessageProperties to extract the ip
return ip;
}
Run Code Online (Sandbox Code Playgroud)
我将能够在测试场景中切换实现:
[Test]
Public void DoSomethingTest()
{
//Arrange...
// Mock MessageProperties so that we can manipulate the ip address in the message
MessagePropertiesHelper.SwitchCurrent(() => new MessageProperties());
// Assert.
...
}
Run Code Online (Sandbox Code Playgroud)
在这里您可以找到我对类似问题的答案:https : //stackoverflow.com/a/27159831/2131067。
归档时间: |
|
查看次数: |
2596 次 |
最近记录: |