我的项目中有一个json文件,我想正确测试反序列化。我想使用嵌入式资源来执行此操作。但是我无法找到获取json文件的正确方法(目前与我的测试文件位于同一文件夹中)。到目前为止,我已经尝试了以下方法:
[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);
}
这不适用于'ReadToEnd'不是有效的方法。我已经尝试过'ReadAsStream',但这会引发错误,我无法将流转换为字符串。
有人能指出我正确的方向吗?谢谢
请确保将Build Action
文件的Rating.json
设置为Embedded Resource
。使用GetManifestResourceStream
和StreamReader
的一种解决方案可以是:
[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; }
}
JSON文件的样本内容。
//Content of "Rating.json" file
[
{
"ID": 1,
"Number": 1001
},
{
"ID": 2,
"Number": 1002
},
{
"ID": 3,
"Number": 1003
},
{
"ID": 4,
"Number": 1004
}
]