Unit testing FTPWebRequest/FTpWebResponse
How would you un开发者_C百科it test FTPWebRequest and FTPWebResponse through MOQ.
You can't mock FTPWebRequest or FTPWebResponse with Moq, because it only allows you to mock interfaces or abstract classes. And it doesn't look like MS was thinking about testability when they wrote most of the System.Net namespace. That's the primary reason I've moved away from Moq to RhinoMocks.
You'll need to build your own FTPWeb* objects and pass them to your handler.
Not possible with Mock also because FTPWebResponse
doesn't have constructors exposed to allow something to be derived from it.
Here is how I wrote my test in similar situation.
Method under test: ExceptionContainsFileNotFound(Exception ex)
contains following logic:
if (ex is WebException)
{
var response = (ex as WebException).Response;
if (response is FtpWebResponse)
{
if ((response as FtpWebResponse).StatusCode == FtpFileNotFoundStatus)
{
return true;
}
}
}
In order to test it I implemented quick trick.
try
{
var request = WebRequest.Create("ftp://notexistingfptsite/");
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.GetResponse();
}
catch (WebException e)
{
// trick :)
classUnderTest.FtpFileNotFoundStatus = FtpStatusCode.Undefined;
var fileNotFoundStatus = classUnderTest.ExceptionContainsFileNotFound(e);
Assert.That(fileNotFoundStatus, Is.True);
}
(Of course FtpFileNotFoundStatus is not exposed to the World.)
For that i use Rhino frameWork.
It can handle instance creation even if there is no public constructor, read only properties and more.
Example:
var ftpWebResponse = Rhino.Mocks.MockRepository.GenerateStub<FtpWebResponse>();
ftpWebResponse.Stub(f=>f.StatusCode).Return(FtpStatusCode.AccountNeeded);
精彩评论