Unit test for Ping / PingReply - Mocking?

I was hoping to find a way to unit test my pinging function or be able to simulate RhinoMocks

Here is a simple code example that I would like to have in a unit test:

public PingReply PingMachine(string machineName)
{
    Ping ping = new Ping();
    return ping.Send(machineName);
}

public bool IsOnline(string machineName)
{
    var reply = PingMachine(machineName);
    if (reply.Status == IPStatus.Success)
    {
        return true;
    }
    return false;
}

Besides creating my own IPing interface and creating Ping in IPing and adding another constructor and working for this, is there a way to easily unit test, or should I not spend my time on it?

+3
source share
2 answers

It looks like you already know a good approach to ensure that your code can be tested: depending on the abstractions. Do not use Ping, use, IPingand provide IPingthrough the constructor to the class that will use it.

IOC, Ninject, , .

, " " .

: , IsOnline(string machineName). , - , . IsOnline! . , ping, .

+2

, , - new Ping(). - , Send , . Factory , , new Ping(), ping factory . :

// some minor injection work
public TestedClass(IPingFactory pingsFactory)
{
    this.pingsFactory = pingsFactory;
}

public PingReply PingMachine(string machineName)
{
    IPing ping = pingsFactory.Create();
    return ping.Send(machineName);
}
+1

All Articles