fluentassertions / fluentassertions.aspnetcore.mvc

Fluent Assertions extensions for ASP.NET Core MVC

Repository from Github https://github.comfluentassertions/fluentassertions.aspnetcore.mvcRepository from Github https://github.comfluentassertions/fluentassertions.aspnetcore.mvc

Add shorthand support for typed ObjectResult assertions

ArwynFr opened this issue · comments

It would be a nice feature to add generic shorthand methods for all results that return an object:

actual.Should().BeCreatedResult<T>().Which.Should().Be(expected);

Instead of:

actual.Should().BeCreatedResult().Value.Should().BeOfType<T>().Which.Should().Be(expected);

Testers that still need to access the result object could still use the longer version, those who only need to validate the returned object could use the shorter one.

It would be quite a lot of work to make a generic and a non-generic variant for that. There is not only the created result but several other similar things also.
But you can shorthand it somewhat. Try this:
actual.Should().BeCreatedResult().ValueAs<T>().Should().Be(expected);
The ValueAs validates the type and returns with it.

Here is what I wrote in my project :

internal static class FluentAssertionExtensions
{
  public static AndWhichConstraint<ObjectAssertions, T> BeCreatedResult<T>(this ActionResultAssertions assertion, string reason = "", params object[] reasonArgs)
  {
    return assertion.BeCreatedResult(reason, reasonArgs)
      .Value.Should().BeOfType<T>(reason, reasonArgs);
  }

  public static AndWhichConstraint<ObjectAssertions, T> BeOkObjectResult<T>(this ActionResultAssertions assertion, string reason = "", params object[] reasonArgs)
  {
    return assertion.BeOkObjectResult(reason, reasonArgs)
      .Value.Should().BeOfType<T>(reason, reasonArgs);
  }
}

I will try with ValueAs<T> though, didn't know it existed.
Feel free to close if you are not interested in providing this feature.

If it returns with the value itself then I think the method name doesn't represent the behavior anymore.
I close this issue since ValueAs() is acceptable alternative.