c# – 单元测试webapi异步操作

我是单元测试的新手,但我试着试着改善我编写的代码质量.

我创建了一个webapi2项目,它返回了一个客户

   public async Task<IHttpActionResult> GetCustomer([FromUri]int id)
    {
         var customer = await _repository.FindCustomerAsync(id);
         return Ok(customer);
    }

我的存储库

 public async Task<Customer> FindCustomerAsync(int id)
    {
        using (var context = new MyContext())
        {
            var result = await context.Customers.FindAsync(id);
            return result;    
        }

    }

以前我没有返回异步任务,因为它非常容易测试.将操作迁移到异步任务使我有点难以测试.

我正在使用Moq和Xunit,我在单元测试中的尝试看起来像

 [Fact()]
    public async void GetCustomer()
    {
        var id = 2;

        _customerMock.Setup(x => x.FindCustomerAsync(id))
            .Returns(Task.FromResult(FakeCustomers()
            .SingleOrDefault(cust => cust.customerID == id)));


        var controller = new CustomersController(_customerMock.Object).GetCustomer(id);
        var result = await controller as Customer;

        Assert.NotNull(result);

        //Assert.IsType<OkNegotiatedContentResult<Customer>>(negotiatedResult);
        //Assert.Equal(negotiatedResult.Content.customerID, id);
    }

我的假客户

  private IQueryable<Customer> FakeCustomers()
    {
        return new List<Customer>()
    {
        new Customer()
        {
            customerID = 1,
            firstName = "Brian",
            lastName = "Smith"
        },
        new Customer()
        {
            customerID = 2,
            firstName = "Tom",
        }
    }.AsQueryable();
    }

尝试转换为Customer {“对象引用未设置为对象的实例时”测试始终失败.

我的测试我做错了什么?

最佳答案 你能这样试试吗?:

[Fact()]
public async void GetCustomer()
{
    var id = 2;

    _customerMock.Setup(x => x.FindCustomerAsync(id))
        .Returns(Task.FromResult(new Customer()
                 {
                  customerID = 2,
                  firstName = "Tom",
                 }));


    var controller = new CustomersController(_customerMock.Object).GetCustomer(id);
    var result = await controller as Customer;

    Assert.NotNull(result);
}
点赞