gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:09:23 25 4
gpt4 key购买 nike

我是单元测试的新手,但我正在努力了解它以尝试提高我编写的代码的质量。

我创建了一个返回客户的 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 {"Object reference not set to an instance of an object."时,测试总是失败。}

我的测试做错了什么?

最佳答案

你可以这样试试吗?:

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

关于c# - 单元测试 webapi 异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21536684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com