Skip to main content

_csharp

Example

To start things off let's include our requisite classes for our test framework (e.g., NUnit.Framework), driving the browser with Selenium (e.g., OpenQA.Selenium, etc.), an HTTP library to handle our HEAD request (e.g., System.Net), and start our class with some setup and teardown methods.

// filename: FileDownloadRevisited.cs
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System.Net;

public class FileDownloadRevisited
{

IWebDriver Driver;

[SetUp]
public void SetUp()
{
Driver = new FirefoxDriver();
}

[TearDown]
public void TearDown()
{
Driver.Quit();
}
// ...

Now we're ready to wire up our test.

It's just a simple matter of visiting the page with download links, grabbing a URL from one of them, and performing a HEAD request with it.

// filename: FileDownloadRevisited.cs
// ...
[Test]
public void CheckFileDownloadWithoutBrowser()
{
Driver.Navigate().GoToUrl("http://the-internet.herokuapp.com/download");
string FileURL = Driver.FindElement(By.CssSelector(".example a")).GetAttribute("href");
var Request = (HttpWebRequest)WebRequest.Create(FileURL);
Request.Method = "HEAD";
WebResponse Response = Request.GetResponse();
Assert.That(Response.ContentType.Equals("application/octet-stream"));
Assert.Greater(Response.ContentLength, 0);
}
}

Once we receive the response we check its header for the content type (e.g., Assert.That(Response.ContentType.Equals("application/octet-stream"));) and content length (e.g., Assert.Greater(Response.ContentLength, 0);) to make sure the file is the correct type and not empty.

Expected Behavior

When you save this and run it (e.g., nunit3-console.exe .\FileDownloadRevisited.sln from the command-line) here is what will happen:

  • Open the browser
  • Load the page
  • Grab the URL of the first download link
  • Perform a HEAD request against it with an HTTP library
  • Store the response headers
  • Check the response headers to see that the file type is correct
  • Check the response headers to see that the file is not empty
  • Close the browser

Summary

Compared to the browser specific configuration with Selenium this is hands-down a leaner, faster, and more maintainable approach.

Happy Testing!