Search code examples
c#xunitfluent-assertions

how to combine multiple assertion using FluentAssertions


I came to know that through FluentAssertions library we can combine multiple assertion in a single like. Just want to know if below 2 assert can be combined in a single line?

        // Act 
        IActionResult actionResult = controller.Update();

        // Assert
        ((ObjectResult)actionResult).StatusCode.Should().Be(200);
        ((ObjectResult)actionResult).Value.Should().BeEquivalentTo("updated");

Solution

  • With the built-in assertions you can compare actionResult against an anonymous object.

    IActionResult actionResult = new ObjectResult("updated")
    {
        StatusCode = 200
    };
    
    var expected = new
    {
        StatusCode = 200,
        Value = "updated"
    };
    
    actionResult.Should().BeEquivalentTo(expected);
    

    For you're specific case you can install FluentAssertions.AspNetCore.Mvc, which lets you write

    actionResult.Should().BeObjectResult()
        .WithStatusCode(200)
        .WithValue("updated");
    

    If you're using Microsoft.AspNet.Mvc and not Microsoft.AspNetCore.Mvc there's