AspNetCore.Docs icon indicating copy to clipboard operation
AspNetCore.Docs copied to clipboard

Using CreatedAtAction with ActionResult<T>

Open Micteu opened this issue 6 years ago • 3 comments

In my mind, the biggest advantage of using ActionResult<T> is making unit tests much cleaner. If I used this document's example CreateAsync method in a unit test, my result object's Value property would be null, and its Result property would be set. If I wanted to verify that I am returning the product object as the value from this method, I would have to do something like ((CreatedAtActionResult)result.Result).Value as Product in order to actually get the value back. This defeats the purpose of using ActionResult<T> and actually makes it more complicated than using IActionResult. Is there a way to return a 201 status with ActionResult<T> without making my unit tests horrible?


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Micteu avatar May 24 '19 20:05 Micteu

I had to do the same...

// Act
var createdAtActionResult = await bprsDtFichaVsitaBancaPrvcdController.PostBprsDtFichaVsitaBancaPrvcd(bprsDtFichaVsitaBancaPrvcd);

var item = (BprsDtFichaVsitaBancaPrvcd)((CreatedAtActionResult)createdAtActionResult.Result).Value;

// Assert
Assert.IsType<BprsDtFichaVsitaBancaPrvcd>(item);

Assert.Equal(bprsDtFichaVsitaBancaPrvcd.FecVst, item.FecVst);

blogcraft avatar Aug 09 '19 15:08 blogcraft

I have the same issues that some types can be returned directly like return model. Some others (like ActionResult<IEnumerable<MyObject>>) have to be wrapped as return Ok(model).

I have not taken a look at it in detail but it seems that there are some issues. As you both wrote before: Because of this you have different tests and the "maybe/maybe not" wrapping it doesn't make it easier.

mbedded avatar Feb 05 '20 08:02 mbedded

Moved to Controller action return types container issue #18092

Rick-Anderson avatar May 01 '20 20:05 Rick-Anderson

This is being updated for .NET 7. See https://github.com/dotnet/AspNetCore.Docs.Samples/pull/84

Rick-Anderson avatar Oct 01 '22 03:10 Rick-Anderson