BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Testing
.NET 1.1+

NUnit File Assertions

Nunit has several types of assertion that can be used in addition to the basic methods provided by the Assert class. One set of assertions, included in the FileAssert class, allows the contents of files to be compared.

FileAssert

NUnit's FileAssert class provides two simple assertions that can be very useful for integration tests where you need to compare the contents of two files. As its name suggests, FileAssert.AreEqual compares two files and passes only if they are identical. The matching is performed by reading the files and comparing their data. The file names and paths do not need to be the same.

As with other, similar assertions, NUnit includes the inverse function, FileAssert.AreNotEqual. This passes if the contents of the two files differ at any point.

The example code below demonstrates the use of both methods. In this case, the files are provided as FileInfo objects. The code assumes that the three mentioned files exist, that "File 1.txt" and "File 1 - Copy.txt" are identical, and that "File 2.txt" contains different information.

[Test]
public void TwoFilesWithTheSameContentsAreEqual()
{
    FileInfo file1 = new FileInfo(@"d:\temp\File 1.txt");
    FileInfo file1copy = new FileInfo(@"d:\temp\File 1 - Copy.txt");

    FileAssert.AreEqual(file1, file1copy);    // Pass
    FileAssert.AreNotEqual(file1, file1copy); // Fail
}

[Test]
public void TwoFilesWithDifferentContentsAreNotEqual()
{
    FileInfo file1 = new FileInfo(@"d:\temp\File 1.txt");
    FileInfo file2 = new FileInfo(@"d:\temp\File 2.txt");

    FileAssert.AreNotEqual(file1, file2); // Pass
    FileAssert.AreEqual(file1, file2);    // Fail
}

The two file references can also be provided as strings containing the paths of the two files, or as streams. The sample below uses two FileStreams.

[Test]
public void MatchingFilesComparedUsingStreamsAreEqual()
{
    using (FileStream file1 = new FileStream(@"d:\temp\File 1.txt", FileMode.Open))
    using (FileStream file1copy = new FileStream(@"d:\temp\File 1 - Copy.txt", FileMode.Open))
    {
        FileAssert.AreEqual(file1, file1copy); // Pass
    }
}
17 January 2016