我正在尝试对方法进行单元测试。但是在此过程中,我必须反序列化以下对象。该对象还有许多其他复杂类型的属性,但是根据我的要求,以下是我如何初始化这些属性。
List<ClueResponse> clueResponses = new List<ClueResponse>
{
new ClueResponse
{
ReportInfo=new ThirdPartyReportInfo
{
ReportRequestDtTm = DateTime.Today,
ReportReceivedDtTm = DateTime.Today,
ReportReferenceNumber = "12345"
},
State="IN"
}
};
此对象设置为HttpResponse内容,然后进行反序列化。
HttpResponseMessage response = new HttpResponseMessage
{
Content = new ObjectContent<List<ClueResponse>>(clueResponses,new JsonMediaTypeFormatter())
};
_mockedBaseApiClient.Setup(m => m.GetAsync("PolicyApi", It.IsAny<string>()))
.ReturnsAsync(response);
反序列化是HttpResponseMessage的扩展方法,为
public static async Task<TResult> Deserialize<TResult>(this HttpResponseMessage response)
{
try
{
using (Stream stream = await response.Content.ReadAsStreamAsync())
using (StreamReader streamReader = new StreamReader(stream))
using (JsonReader textReader = new JsonTextReader(streamReader))
{
JsonSerializer serializer = new JsonSerializer
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore,
};
return serializer.Deserialize<TResult>(textReader);
}
}
catch (Exception ex)
{
ex.Data.Add("StatusCode", response.StatusCode);
ex.Data.Add("ReasonPhrase", response.ReasonPhrase);
throw new SerializationException("Failed to deserialize", ex);
}
}
但是反序列化之后,我没有正确反序列化对象。我得到所有属性的所有null,即使是ReportInfo
var clueResponses= await clueResponseMessage.Deserialize<List<ClueResponse>>();
内容反序列化到列表中,但是每个Clue对象的所有属性都为空。