There may be occassions during the course of developing a software project that you may need to store a text file or any binary type file within the resources of project, and make use of it.
In my example below, developing a generic CSV reader class, which is basically wrapper class around a CSV parser utility, LINQtoCSV
What if we wanted to test a few different CSV files at it of various lengths and check the out put etc. Maybe we need to create some integration tests Unit Tests to esnure it operated as expected, and cover any edge type cases.
Lets set up a test library with nUnit, rhino and other TDD components. We may want to store the CSV files within the Test library, primarily so other developers could execute the tests without having to copy files around.
It’s a simple enough process of adding files to resources, but how do we get them out again?
The wrong solutions
The following solution on StackOverflow. Seems to indicate you need to create some private method and make use of reflection on the current executing assembly.
The solution works, but taking a step back and thinking about it. There has to be a simpler method.
The easy method
A bit of good old-fashioned RTFM! and this page in particular! Adding and Editing Resources (Visual C#)
All that is needed to get a file in the resources and view the properties window and set the File Type to Binary
It is then a trivial matter of passing the byte array to my class in one line of code!
FileName is the name of the file in the Resource.
We can now use this in a simple unit test
I appreciate the fact that many purists will take a look at these unit test, and regard them more as integration tests, in that the test is testing actual outcomes of a unit of work, in that there is still a dependency on LinqToCsv being present and that it does some kind of work. However, in my case I did want the ability to test this code, and ensure that the results it emits are as expected. I also wanted a method that I could quickly and repeatedly run these tests.
I would love to hear your views on this. If you feel that you could provide me with a better solution or even improve my current solution I would certainly love to hear it, feel free to contact me or leave a note in the comment section below.
A unique background as business owner, marketing, software development and business development ensures that he can offer the optimum business consultancy services across a wide spectrum of business challenges.
Latest posts by Gary Woodfine (see all)
- Book Review: Java by Comparison - Jan 7, 2019
- Book Review : The 4 Hour Work Week - Dec 28, 2018
- Happy 4th Blog Birthday – A blogging year in review - Dec 6, 2018