質問

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