How to create a fake FtpWebResponse

2019-08-02 20:57发布

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

2条回答
Viruses.
2楼-- · 2019-08-02 21:21

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);
查看更多
来,给爷笑一个
3楼-- · 2019-08-02 21:27

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);
查看更多
登录 后发表回答