Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit tests code with Dns.GetHostEntry(hostNameOrIp) dependency

I have code that uses Dns.GetHostEntry(hostNameOrIp) and I want to check scenario that one time this function return real values but in some time(when I decide) this function throw exception.
Currently I am using MSTest framework in visual studio 2010. Someone has idea what is the easiest way to achieve it?

like image 803
ilay zeidman Avatar asked Jan 11 '23 14:01

ilay zeidman


1 Answers

Easiest way to achieve it is creating wrapper for this static methods:

public class DnsWrapper : IDnsWrapper
{
    public IPHostEntry GetHostEntry(string hostNameOrAddress)
    {
         Dns.GetHostEntry(hostNameOrAddress);
    }
}

And make your code depend on this interface:

public interface IDnsWrapper
{
   IPHostEntry GetHostEntry(string hostNameOrAddress);
}

Now mocking of this dependency is very easy with any mocking library. E.g with Moq:

Mock<IDnsWrapper> dnsMock = new Mock<IDnsWrapper>();
dnsMock.Setup(d => d.GetHostEntry(It.IsAny<string>()))
       .Throws(new SocketException());

var yourClass = new YourClass(dnsMock.Object); // inject interface implementation
yourClass.DoSomethingWhichGetHostsEntry();
like image 120
Sergey Berezovskiy Avatar answered Jan 19 '23 00:01

Sergey Berezovskiy