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?

有帮助吗?

解决方案

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();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top