Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
xUnit: A test object for IActionResult types, wrapping JsonResult, NoContentResult, ObjectResult etc.
using System;
using Microsoft.AspNetCore.Mvc;
using Xunit;
namespace My.Tests.Models
{
/// <summary>
/// Defines all subclasses of <see cref="ActionResult"/>
/// that have status codes and <see cref="object"/> values.
/// </summary>
public class ObjectValueActionResult
{
/// <summary>
/// Initializes a new instance of the <see cref="ObjectValueActionResult"/> class.
/// </summary>
/// <param name="result">The result.</param>
/// <remarks>
/// The majority of <see cref="IActionResult"/> instances like <see cref="OkObjectResult"/> derive
/// from <see cref="ObjectResult"/>.
/// </remarks>
public ObjectValueActionResult(IActionResult result)
{
Assert.NotNull(result);
switch (result)
{
case JsonResult j:
this.Value = j.Value;
this.StatusCode = j.StatusCode;
break;
case NoContentResult n:
this.StatusCode = n.StatusCode;
break;
case ObjectResult o:
this.Value = o.Value;
this.StatusCode = o.StatusCode;
break;
default:
throw new NotImplementedException($"The expected {nameof(IAsyncResult)} type is not here.");
}
}
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <value>
/// The value.
/// </value>
public object Value { get; set; }
/// <summary>Gets or sets the HTTP status code.</summary>
public int? StatusCode { get; set; }
}
}
@BryanWilhite

This comment has been minimized.

Copy link
Owner Author

commented May 15, 2019

JsonResult and ObjectResult do not derive from each other and controller methods are often designed to return either type using IActionResult or ActionResult; i baffles me why JsonResult and ObjectResult are so unrelated—surely someone at Microsoft (like @DamianEdwards) can explain

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.