Skip to content

Instantly share code, notes, and snippets.

@Flayed
Created March 23, 2018 12:00
Show Gist options
  • Select an option

  • Save Flayed/6f10349a7ae7a9aba54c7bd76eaf73a5 to your computer and use it in GitHub Desktop.

Select an option

Save Flayed/6f10349a7ae7a9aba54c7bd76eaf73a5 to your computer and use it in GitHub Desktop.
Unit testing IActionResult
public class ControllerTestBase
{
protected void Is<T>(IActionResult result, HttpStatusCode statusCode) where T : StatusCodeResult
{
var r = result as T;
r.Should().NotBeNull();
r.StatusCode.Should().Be((int)statusCode);
}
protected TPayload Is<TResult, TPayload>(IActionResult result, HttpStatusCode statusCode) where TResult : ObjectResult
{
var r = result as TResult;
r.Should().NotBeNull();
r.StatusCode.Should().Be((int)statusCode);
r.Value.Should().BeAssignableTo<TPayload>();
return (TPayload)r.Value;
}
}
public class MyControllerTest: ControllerTestBase
{
[Fact(DisplayName="MyMethod should return NoContent if everything goes well")]
public async Task MyMethod_NoErrors_ReturnsNoContent()
{
var myService = new Mock<IMyService>();
myService.Setup(ms => ms.ServiceMethod(It.IsAny<string>())).ReturnsAsync(true);
var myController = new MyController(myService.Object);
var result = await myController.MyMethod("potato");
Is<NoContentResult>(result, HttpStatusCode.NoContent);
}
[Fact(DisplayName="MyMethod should return InternalServerError if MyService throws an exception")]
public async Task MyMethod_NoErrors_ReturnsNoContent()
{
var myService = new Mock<IMyService>();
myService.Setup(ms => ms.ServiceMethod(It.IsAny<string>())).ThrowsAsync(new Exception());
var myController = new MyController(myService.Object);
var result = await myController.MyMethod("potato");
Is<InternalServerErrorResult>(result, HttpStatusCode.InternalServerError);
}
[Fact(DisplayName="MyResultMethod should return Ok if everything goes well")]
public async Task MyResultMethod_NoErrors_ReturnsOk()
{
string expected = "pancakes";
var myService = new Mock<IMyService>();
myService.Setup(ms => ms.ServiceResultMethod(It.IsAny<string>())).ReturnsAsync(expected);
var myController = new MyController(myService.Object);
var result = await myController.MyResultMethod("potato");
// Provide the ObjectResult type and the expected payload type
var stringResult = Is<OkObjectResult, string>(result);
stringResult.Should().Be(expected);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment