Unit testing controller methods which return IActionResult

前端 未结 4 835
时光说笑
时光说笑 2020-12-05 09:07

I\'m in the process of building an ASP.NET Core WebAPI and I\'m attempting to write unit tests for the controllers. Most examples I\'ve found are from the older WebAPI/WebA

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 09:54

    Assuming something like the

    public IActionResult GetOrders() {
        var orders = repository.All();
        return Ok(orders);
    }
    

    the controller in this case is returning an OkObjectResult class.

    Cast the result to the type of what you are returning in the method and perform your assert on that

    [Fact]
    public void GetOrders_WithOrdersInRepo_ReturnsOk() {
        // arrange
        var controller = new OrdersController(new MockRepository());
    
        // act
        var result = controller.GetOrders();
        var okResult = result as OkObjectResult;
    
        // assert
        Assert.IsNotNull(okResult);
        Assert.AreEqual(200, okResult.StatusCode);
    }
    

提交回复
热议问题