Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test for Ping / PingReply - Mocking?

I was hoping to find a way to unit test my pinging functionality or be able to Mock it with RhinoMocks

Here is a simple example of the code I would like to be able to 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 making Ping into IPing and adding another constructor and bunch of work for that, is there a way to easily unit test this, or should I not waste my time with it?

like image 882
John Avatar asked Oct 20 '25 16:10

John


1 Answers

It sounds like you already know a good approach to making your code testable: Depend on abstractions. Don't use a Ping, use IPing, and have the IPing be provided via constructor to the class that's going to use it.

Look into an IOC container like Ninject to make your life easier, especially if you're wiring up a lot of dependencies.

As for whether you should or not, my answer to "should I make this code testable and write tests for it" is always a resounding YES.

Think of it like this: You have this method, IsOnline(string machineName). Let's say you're writing code somewhere else, and you want to test that code. But that code uses IsOnline! Suddenly, testing it just got harder. If you could mock your ping providing class, testing it would be a breeze.

like image 122
Daniel Mann Avatar answered Oct 23 '25 05:10

Daniel Mann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!