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.
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()
?
[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(e.g. implement an interface and mock the implementation of the interface)?
I would wrap the call with a static helper:
Then in
GetIpFromWcfMessage
I would call:And I would be able to switch the implementation in the test scenario:
Here you can find my answer to similar problem: https://stackoverflow.com/a/27159831/2131067.