1

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

DJ Burb
  • 2,346
  • 2
  • 29
  • 38

2 Answers2

1

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);
DJ Burb
  • 2,346
  • 2
  • 29
  • 38
  • It should be noted that this answer requires Visual Studio Premium or above. There is an alternative called Prig which I haven't used that could possibly help but otherwise this should be considered a *premium solution* which won't work for all. – Maffelu Aug 31 '15 at 11:59
  • It should be also noted that it needs to added the System.fakes file. https://stackoverflow.com/questions/26914058/why-doesnt-microsoft-fakes-create-shimftpwebrequest – erhan355 Apr 13 '18 at 11:12
0

Rhino framework can do it. And it can be added by Nuget:

Example:

var ftpWebResponse = Rhino.Mocks.MockRepository.GenerateStub<FtpWebResponse>();
ftpWebResponse.Stub(f=>f.StatusCode).Return(FtpStatusCode.AccountNeeded);
MiguelSlv
  • 14,067
  • 15
  • 102
  • 169