HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

FTP Download Helper Method

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
downloadftphelpermethod

Problem

I'm currently using an Open Source FTP library in all my projects as I've never managed to code a decent FTP Helper Library based on the C# 4.0 API.

What do you think about this approach? I'm not quite versed in TDD but ideally I'd like to make this class as testable as possible.

public void DownloadFile(string host, string file, string user, string pass, string path)
{
    if (!String.IsNullOrWhiteSpace(host) && !String.IsNullOrWhiteSpace(file))
    {
        Uri addr = new Uri(host + file);

        using (WebClient client = new WebClient())
        {
            if (!String.IsNullOrWhiteSpace(user) && !String.IsNullOrWhiteSpace(pass))
            {
                client.Credentials = new NetworkCredential(user, pass);
            }

            if (!String.IsNullOrWhiteSpace(path))
            {
                client.DownloadFile(addr, path);
            }
        }
    }
}

Solution

Unit testing means that automated tests can run in isolation from any dependencies (such as other classes, but also the environment).

The DownloadFile method has a hard-coded dependency on WebClient and thus on the environment. It can't be used without using the network and (presumably) a remote service. Even if you decide to hit localhost, you'll need to set up an FTP server on your own machine, and that counts as an external dependency as well. Thus the method can't be unit tested as is.

One possible remedy is to hide WebClient behind an appropriate interface (you could call it IWebClient) and inject that into the class holding the DownloadFile method.

In general, however, such methods are better left as Humble Objects and perhaps subjected to integration tests.

Context

StackExchange Code Review Q#2114, answer score: 5

Revisions (0)

No revisions yet.