简体   繁体   中英

Unit Test - 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?

eg:

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.

Use the file: 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.

The hint by @RPM1984 suggests the answer. I just ran into this issue and the following hack did it for me:

string fqnModified = "\\" + fqn;
Uri uri = new Uri(fqnModified);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM