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
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
[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."}
What I am doing wrong with my test?