How to create a fake FtpWebResponse

南笙酒味 提交于 2020-01-05 08:34:46

问题


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


回答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);



回答2:


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);


来源:https://stackoverflow.com/questions/26282143/how-to-create-a-fake-ftpwebresponse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!