Unit/Integration testing FTP access

2020-08-17 22:16发布

问题:

A member of my Team is writing an application that accesses an external FTP site to download files. Having written the code we would like to be able to do integration testing without using a physical ftp server as it is an external site.

We have done similar things in the past using nDumpster for simulating an smtp server in code and we are wondering if there are any equilivent compliant ftp servers that can be used?

Edit:

I should add that these are not for true unit tests, we have those and mock our ftp implementation.

However we are using WebFtpRequest.Create() in the actual implementation of the interface. So testing this code requires an actual server (unless we register our own protocol in the tests) eventually we will have to test against an actual server!.

We want to be able to start and stop the ftp server in code (much like you can nDumpster) and examine that our calls are correct.

回答1:

I just needed something similar and ended up with solution based on small FTPDMIN command-line FTP server. You can find my solution here: https://github.com/Buthrakaur/FtpIntegrationTesting



回答2:

You should abstract the interface of the code using the FTP server. If you have this interface you can create a stubbed implementation of the FTP communication making your test code not dependent on a specific FTP server as well as improving performance of your tests.

Especially these kinds of dependencies should be abstracted from you normal code to prevent a tight coupling to something that is hard to mock (such as an FTP or Mail server).

I wouldn't want to use a tool like nDumpster but rather swap the implementation which is made possible by good design.



回答3:

You should introduce interface to you FtpService class like this:

interface IFtpService
{
    byte[] Download(string fileName);
    bool Upload(byte[] data);
}

Implement this interface:

public class FtpService: IFtpService
{
    //public byte[] Donload implementation goes here
    //public bool Upload(byte[] data) implementation goes here

}

At your unit tests you should use Mocks to mock IFtpService and play with it: create your expectations, create expectations for common Ftp exceptions etc.

This gives you separation from real FTP infrastructure, your tests doesn't have dependencies on hardware (network connection).



回答4:

You can include Rebex FileServer in your project or unit tests, it is supported on many platforms, including .NET

A small how to guide can be found at the using Rebex blog

It is not free and I am not affiliated in any way.

EDIT: I have subsequently discovered this delightful "poor mans FTP Server", which includes source code (MIT license).



标签: c# testing ftp