1

I have a json file in my project that I want to test deserializes correctly. I want to use embedded resources to do this. However I can't work out the correct way to get the json file (which is in the same folder as my test file for now). So far I have tried the following:

[Test]
        public void JsonDeserializesTest()
        {
            var reader = new EmbeddedResourceReader(typeof(RatingComponentTests).Assembly, "Components\\UserFeedback");
            var json = reader.ReadToEnd("Rating.json");
            var jsonData = JsonConvert.DeserializeObject<RatingData>(json);
            Assert.IsNotNull(jsonData.results);
        }

This isn't working with 'ReadToEnd' not being a valid method. I have tried 'ReadAsStream' but this throws the error that I cannot convert a stream to a string.

Can anyone please point me in the right direction? Thanks

Jordan1993
  • 864
  • 1
  • 10
  • 28
  • Have a look at https://stackoverflow.com/questions/3314140/how-to-read-embedded-resource-text-file – MKR Jan 28 '20 at 16:40

1 Answers1

2

Please make sure to set Build Action of Rating.json file as Embedded Resource. One solution using GetManifestResourceStream and StreamReader could be as:

[Test]
public void JsonDeserializesTest()
{
  //WindowsTestApp is namespace of project
  using (Stream stream = Assembly.GetExecutingAssembly().
                         GetManifestResourceStream("WindowsTestApp.Rating.json"))
  using (StreamReader reader = new StreamReader(stream))
  {
      var jsonFileContent = reader.ReadToEnd();
      var jsonData = JsonConvert.DeserializeObject<IList<RatingData>>(jsonFileContent);
      Assert.IsNotNull(jsonData);
  }

}

//Test class of json data
public class RatingData
{
    public int ID { get; set; }
    public int Number { get; set; }
}

The sample contents of JSON file.

//Content of "Rating.json" file

[
  {
    "ID": 1,
    "Number": 1001
  },
  {
    "ID": 2,
    "Number": 1002
  },
  {
    "ID": 3,
    "Number": 1003
  },
  {
    "ID": 4,
    "Number": 1004
  }
]
MKR
  • 19,739
  • 4
  • 23
  • 33