Unit tests with Nunit in function with Jsonresult type return

Asked

Viewed 139 times

0

I’m trying to do unit testing in the following function (there are more ifs, but I believe this is enough to illustrate), using Nunit. The problem is that I am unable to treat the return of the Jsonresult type. When running the test, the result is

Message: Expected: True But was: <empty>

How can I get around that?

Function (is in a Controller):

[HttpPost]
    public JsonResult ChangePassword(string password, string new_password, string confirm_password, string email)
    {
        //string email = Seguridad.Session.GetUserMail();

        if (new_password != confirm_password)
            return Json(new { success = false, message = "As senhas não coincidem" });

    }

Testing:

[TestFixture]
public class CandidatoControllerTestChangePassword
{
    [Test]
    public void TestChangeValidPassword()
    {
        var controller = new CandidatoController();
        var result = controller.ChangePassword("password", "newpassword", "newpassword", "[email protected]") as JsonResult;
        var data = JsonConvert.SerializeObject(result.Data);
        var deserializedData = JsonConvert.DeserializeObject<dynamic>(data);

        Assert.AreEqual(true, deserializedData.success);

    }
}
  • result. Date returns JSON with value?

  • 1

    Only with this if you can not guarantee anything... you are passing two identical passwords, which in the presented code would not return anything...

1 answer

1

You’d have to do it that way:

[TestFixture]
public class CandidatoControllerTestChangePassword
{
    [Test]
    public void TestChangeValidPassword()
    {
        var controller = new CandidatoController();
        var result = controller.ChangePassword("password", "newpassword", "newpassword", "[email protected]") as JsonResult;
        var data = JsonConvert.SerializeObject(result.Data);

        //O Tipo aqui é dynamic e não 'var' e DeserializeObject não precisa do tipo entre <>
        dynamic json = JsonConvert.DeserializeObject(data);

        //Realiza a conversão antes
        bool resultado = false;
        bool.TryParse(json.success.ToString() out resultado);

        //Apenas compara o valor de resultado no AreEqual
        Assert.AreEqual(true, resultado);

    }
}
  • 1

    an error appeared "The operator as must be used with a reference type or an annulable type ("bool" is a type of non-avoidable value)"

  • check if Success is written in the correct way, example: if the object is written in capital letters (Success) in the same way as the Dynamic object, for if a Dynamic object you only catch this type error at runtime

Browser other questions tagged

You are not signed in. Login or sign up in order to post.