单元测试web api异步操作

时间:2014-02-03 20:07:17

标签: c# moq async-await xunit.net

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

我创建了一个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);
    }

我的FakeCustomers

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

尝试转换为Customer {“对象引用未设置为对象的实例时”测试总是失败。}}

我的测试错误了吗?

1 个答案:

答案 0 :(得分:2)

你能这样试试吗?:

[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);
}