I'm new to unit testing, but trying to raise my head to try to improve the quality of the code I'm writing.
I created a webapi2 project that returns the client as
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;
}
}
I did not return an asynchronous task before, it was very easy to check. Migrating the action to an asynchronous task made me a little more difficult to verify.
I am using Moq and Xunit, and my unit test attempt looks like
[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);
}
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 pass to the Client {"The object reference is not set to the object instance." }
What am I doing wrong with my test?
source
share