Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit test parser with large string input

I like the suggestion here:

SO question

It suggests using this code:

public class SettingsReader()
{
    public SettingsReader(System.IO.StreamReader reader)
    {
        // read contents of stream...
    }
}

// In production code:
new SettingsReader(new StreamReader(File.Open("settings.xml")));

// In unit test:
new SettingsReader(new StringReader("<settings>dummy settings</settings>"));

I am just wondering what the best practice is to 'supply' large test strings (i.e. several lines of the file to be parsed).

like image 784
cs0815 Avatar asked Jan 16 '13 08:01

cs0815


2 Answers

One common approach is to add a file with the test data to the resources of the unit test assembly and read that data in the unit test.

like image 178
Daniel Hilgarth Avatar answered Nov 07 '22 01:11

Daniel Hilgarth


Just add a separate file as assembly embedded resource and load it in unit test.

Use Assebmly.GetManifestResourceStream method to load the embedded file.

using (var stream = Assembly.GetExecutingAssembly()
       .GetManifestResourceStream(typeof(YourUnitTest), filename))
using(var reader = new StreamReader(stream))
{
    var fileContent = reader.ReadToEnd();
}
like image 2
Jakub Konecki Avatar answered Nov 07 '22 00:11

Jakub Konecki