cs0815
cs0815

Reputation: 17408

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).

Upvotes: 5

Views: 1737

Answers (4)

Matthew Watson
Matthew Watson

Reputation: 109597

The easiest way is to just add a file to the unit test project, and use that. Set the file's properties to "Build Action = None" and "Copy to Output Directory = Copy if newer" and then you can just assume the file is in the same folder as the unit test executable.

I find that putting a large string into the source code itself makes it harder to read because of the way you have to format strings in the source code - especially if the text contains characters that must be escaped. Much nicer to have a text file with all the data, IMHO.

If you would like to share the test data between unit test projects, you can do so by placing the file somewhere under source control and then add to the project a link to the file (rather than a copy of the file). That way you only have one copy of the original source file to maintain.

Upvotes: 0

Jakub Konecki
Jakub Konecki

Reputation: 46008

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();
}

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

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.

Upvotes: 3

Richard Schneider
Richard Schneider

Reputation: 35477

For unit tests its best to show the test data directly in the code, instead of using an embedded resource file.

var settings = @"
<settings>
  <a>1</a>
  <b>2</b>
</settings>";

new SettingsReader(new StringReader(settings));

Upvotes: 2

Related Questions