How to unit test an Action method which returns JsonResult?

前端 未结 8 1959
我在风中等你
我在风中等你 2020-12-13 12:38

If I have a controller like this:

[HttpPost]
public JsonResult FindStuff(string query) 
{
   var results = _repo.GetStuff(query);
   var jsonResult = results         


        
8条回答
  •  误落风尘
    2020-12-13 13:04

    Here's one I use, perhaps it is of use to anyone. It tests an action that returns a JSON object for use in clientside functionality. It uses Moq and FluentAssertions.

    [TestMethod]
    public void GetActivationcode_Should_Return_JSON_With_Filled_Model()
    {
        // Arrange...
        ActivatiecodeController activatiecodeController = this.ActivatiecodeControllerFactory();
        CodeModel model = new CodeModel { Activation = "XYZZY", Lifespan = 10000 };
        this.deviceActivatieModelBuilder.Setup(x => x.GenereerNieuweActivatiecode()).Returns(model);
    
        // Act...
        var result = activatiecodeController.GetActivationcode() as JsonResult;
    
        // Assert...
        ((CodeModel)result.Data).Activation.Should().Be("XYZZY");
        ((CodeModel)result.Data).Lifespan.Should().Be(10000);
    }
    

提交回复
热议问题