1

I'm writing unit tests for JSON responses.

This is my method:

  public  ActionResult AddMakeAliasData(MakeAliasModel makeAliasModel)
    {
        if (!ModelState.IsValid)
        {
            ModelState.LogModelStateError();
            throw new BusinessException("COMMON_ERROR");
        }

        var response = _vehicleDataBusinessService.AddMakeAliasData(makeAliasModel);
        return Json(response);
    }

I wrote a test case for this:

  [Test]
    public void ShouldReturnJsonInAddMakeAlias()
    {
        //Arrange
        var data = new GetVehicleDataAliases
        {
            ErrorMessage = null,
            ErrorCode = null,
            MakeDtos = new List<VehicleDto>(),
            Success = true,
            FindData = new List<SearchData>()
        };
      
        mockVehicleDataBusinessService.Setup(x => x.AddMakeAliasData(It.IsAny<MakeAliasModel>())).Returns(() => data);
        var sut = new VehicleDataController(mockVehicleDataBusinessService.Object);
        //Act
        var result = sut.AddMakeAliasData(makeAliasModel) as JsonResult;
        //Assert
        Assert.AreEqual(data,result);
    }

But I am getting this error:

 Expected: <Message.Response.GetVehicleDataAliases>
 But was: <System.JsonResult>

There Is something wrong in the assertion or my expected result is not proper.

What should I do? For checking the JSON result how should I do that?

Andrew
  • 307
  • 7
  • 13
  • 1
    Can you try this, Assert.AreEqual(data,result.Value); – Priyan Perera Apr 02 '18 at 04:42
  • I really must urge you away from using `It.IsAny`. You have the actual value used for that parameter. See [this question](https://stackoverflow.com/questions/49332471/mock-verify-invocation) and the comments on the not accepted answer, then the accepted answer. – Richardissimo Apr 02 '18 at 04:47
  • How about `Assert.AreEqual(Json(data),result);` – Richardissimo Apr 02 '18 at 04:55
  • @PriyanPerera it worked.. but what if exception is thrown at that time how should i check for jsonresult –  Apr 02 '18 at 05:24
  • @Richardissimo i tried your way ... it says that non-invocable member cannot be used as a memeber –  Apr 02 '18 at 05:26
  • I believe you should write a separate test for testing exceptions. This SO question is a good starter. https://stackoverflow.com/questions/3407765/nunit-expected-exceptions – Priyan Perera Apr 02 '18 at 05:35
  • I'd suggest encapsulating the `Json` method in a dependency which is injected into your controller and mock it for your test. – Richardissimo Apr 02 '18 at 05:47

0 Answers0