Search code examples
c#unit-testinguri.net-4.5xunit

Construct URI for local file in project


I have a service which parses JSON from an external API.

This service does the following:

  1. Constructs a URI to the API
  2. Reads the JSON returned
  3. Deserializes into relevant C# objects
  4. Maps to my domain entities
  5. Saves to database

I'm trying to unit-test steps 1-4 (5 is out of scope for this test).

As such, i don't want to be hitting the web api - rather i have a "sample" JSON file stored locally in my test project.

How can i read this file and construct it into a Uri object?

e.g:

var uri = new Uri("myfile.json");

I'm getting an error saying "The URI is not well formed".

The file is set to Build Action: Embedded Resource, and Copy to Output Directory: Copy always.

I'm on C# .NET 4.5 (VS 2012), and using XUnit for my tests.


Solution

  • Use thefile: scheme and the fully qualified path to the output directory, which should be the same as were the test is running from.

    var fqn = Assembly.GetExecutingAssembly().Location;
    var uri = new Uri("file://" + fqn + "/myfile.json");
    

    See http://en.wikipedia.org/wiki/File_URI_scheme for more details.