简体   繁体   English

单元测试webapi异步操作

[英]unit testing a webapi async action

I am new to unit testing but trying to get my head around it to try improve the quality of code I write. 我是单元测试的新手,但我试着试着改善我编写的代码质量。

I have created a webapi2 project that returns a customer like 我创建了一个webapi2项目,它返回了一个客户

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

My repository 我的存储库

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

    }

Previously I was not returning an async task at it was very easy to test. 以前我没有返回异步任务,因为它非常容易测试。 Migrating the action to a async task has made it a little hard for me to test. 将操作迁移到异步任务使我有点难以测试。

I am using Moq and Xunit and my attempt at a unit test looks like 我正在使用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);
    }

My FakeCustomers 我的假客户

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

the test always fails when trying to cast to Customer {"Object reference not set to an instance of an object."} 尝试转换为Customer {“对象引用未设置为对象的实例时”测试始终失败。

What I am doing wrong with my test? 我的测试我做错了什么?

Can you try this way?: 你能这样试试吗?:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM