Search code examples
c#unit-testingasp.net-core

Convert object to model always returns null


I have a project that needs to convert an object from a method in unit test, but when I try to cast the object, it is always null.

var result = (IValueHttpResult)sut.Invoke("TEST");
var okResult = result.Value as LoanProgressResponse; 

okResult always null.

If I debug, I think there is no problem with the result I got from Invoke.

This is the value of result: enter image description here

and this is the value of result.Value enter image description here

and this is the LoanProgressResponse class:

public class LoanProgressResponse
{
    public string response_id { get; set; } = string.Empty;
    public string status_code { get; set; } = string.Empty;
    public string status_description { get; set; } = string.Empty;
    public string current_progress { get; set; } = string.Empty;
    public bool is_approved { get; set; } = false;
}

I tried to explore but still failed like:

LoanProgressResponse okResult = result.Value as LoanProgressResponse;

Am I missing something? I would be glad for any help.


Solution

  • By default, without specifying the generic type for IValueHttpResult, the Value is an object type. You cannot directly cast the Value to LoanProgressResponse type unless you are working with (de)serialization.

    using System.Text.Json;
    
    var result = (IValueHttpResult)sut.Invoke("TEST");
    var okResult = JsonSerializer.Deserialize<LoanProgressResponse>(result.Value.ToString()); 
    

    Otherwise, you have to use IValueHttpResult<Value>.

    var result = (IValueHttpResult<LoanProgressResponse>)sut.Invoke("TEST");
    var okResult = result.Value; 
    

    Retrieve the value using Newtonsoft.Json.

    var okResult = JsonConvert.DeserializeObject<LoanProgressResponse>(JsonConvert.SerializeObject(result.Value!));