Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Tests for comparing text files in NUnit

I have a class that processes a 2 xml files and produces a text file.

I would like to write a bunch of unit / integration tests that can individually pass or fail for this class that do the following:

  1. For input A and B, generate the output.
  2. Compare the contents of the generated file to the contents expected output
  3. When the actual contents differ from the expected contents, fail and display some useful information about the differences.

Below is the prototype for the class along with my first stab at unit tests.

Is there a pattern I should be using for this sort of testing, or do people tend to write zillions of TestX() functions?

Is there a better way to coax text-file differences from NUnit? Should I embed a textfile diff algorithm?


class ReportGenerator
{
    string Generate(string inputPathA, string inputPathB)
    {
        //do stuff
    }
}

[TextFixture]
public class ReportGeneratorTests
{
     static Diff(string pathToExpectedResult, string pathToActualResult)
     {
         using (StreamReader rs1 = File.OpenText(pathToExpectedResult))
         {
             using (StreamReader rs2 = File.OpenText(pathToActualResult))
             {
                 string actualContents = rs2.ReadToEnd();
                 string expectedContents = rs1.ReadToEnd();                  

                 //this works, but the output could be a LOT more useful.
                 Assert.AreEqual(expectedContents, actualContents);
             }
         }
     }

     static TestGenerate(string pathToInputA, string pathToInputB, string pathToExpectedResult)
     {
          ReportGenerator obj = new ReportGenerator();
          string pathToResult = obj.Generate(pathToInputA, pathToInputB);
          Diff(pathToExpectedResult, pathToResult);
     }

     [Test]
     public void TestX()
     {
          TestGenerate("x1.xml", "x2.xml", "x-expected.txt");
     }

     [Test]
     public void TestY()
     {
          TestGenerate("y1.xml", "y2.xml", "y-expected.txt");
     }

     //etc...
}

Update

I'm not interested in testing the diff functionality. I just want to use it to produce more readable failures.

like image 945
Adam Tegen Avatar asked Sep 26 '08 21:09

Adam Tegen


1 Answers

As for the multiple tests with different data, use the NUnit RowTest extension:

using NUnit.Framework.Extensions;

[RowTest]
[Row("x1.xml", "x2.xml", "x-expected.xml")]
[Row("y1.xml", "y2.xml", "y-expected.xml")]
public void TestGenerate(string pathToInputA, string pathToInputB, string pathToExpectedResult)
 {
      ReportGenerator obj = new ReportGenerator();
      string pathToResult = obj.Generate(pathToInputA, pathToInputB);
      Diff(pathToExpectedResult, pathToResult);
 }
like image 162
Adam Tegen Avatar answered Sep 24 '22 20:09

Adam Tegen