Search code examples
c#ftpwebrequestmicrosoft-fakesftpwebresponse

How to create a fake FtpWebResponse


I am trying to fake an FtpWebRequest.GetResponse() for an integration test, but without using a server. What I have been trying to do is the simple return a fake FtpWebResponse but, you are not allowed to access the constructor for the FtpWebResponse because it is internal.

Here is my code:

Production code:

            using (FtpWebResponse response = (FtpWebResponse) ftpWebRequest.GetResponse())
            {
                ftpResponse = new FtpResponse(response.StatusDescription, false);
            }

Test fake I am trying to use to return a fake FtpWebResponse:

            ShimFtpWebRequest.AllInstances.GetResponse = request =>
            {
                FtpWebResponse ftpWebResponse= new FtpWebResponse(/*parameters*/); // not allowed because it is internal
                ftpWebResponse.StatusDescription="blah blah blah";
                return ftpWebResponse;
            };

In the end, all I want to do is return a fake ftpWebResponse for assertion in my test. Any ideas? Thanks


Solution

  • Found the answer. If you Shim the FtpWebResponse, it will allow a constructor:

            FtpResponse response;
    
            using (ShimsContext.Create())
            {
                ShimFtpWebRequest.AllInstances.GetResponse = request => new ShimFtpWebResponse();
                ShimFtpWebResponse.AllInstances.StatusDescriptionGet = getDescritpion => "226 Transfer complete.";
                _ftpConnection.Put(_fileContent);
                response = new FtpResponse("226 Transfer complete.", false);
            }
            Assert.AreEqual(response.Message, "226 Transfer complete.");
            Assert.IsFalse(response.HasError);