Skip to content

Instantly share code, notes, and snippets.

@BryanWilhite
Created May 15, 2019 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BryanWilhite/73f446d8de646b74b74147199577d925 to your computer and use it in GitHub Desktop.
Save BryanWilhite/73f446d8de646b74b74147199577d925 to your computer and use it in GitHub Desktop.
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
Copy link
Author

BryanWilhite 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