I have convereted my IEnumerable function into a (public async Task<List>) however im having issues fixing my unit test for that specific part. Im using fakeiteasy to mock my data, and assert that my result.count == 1 after fetching my data.
However i get this specific error
Unable to cast object of type 'System.Threading.Tasks.Task
1[System.Collections.Generic.List
1[WebAPI__CodeFirst.Classes.Customer]]' to type 'System.Collections.Generic.IEnumerable`1[WebAPI__CodeFirst.Classes.Customer]'.
This is my ICustomerRepository
public interface ICustomerRepository
{
Task<List<Customer>> GetAllCustomers();
}
This is my Test for my getAll
private readonly ICustomerRepository _repo;
private readonly CustomersController _controller;
public CustomerControllerTests()
{
_repo = A.Fake<ICustomerRepository>();
_controller = new CustomersController(_repo);
}
[Fact]
public void GetAll_Returns_All_Customers()
{
// Arrange
var customers = new List<Customer>() { new Customer { customer_ID = 1 } };
A.CallTo(() => _repo.GetAllCustomers()).Returns(customers);
// Act
var result = _controller.GetAll();
// Assert
Assert.Single(result);
}
CodePudding user response:
Your code is asynchronous, and your test is for code that executes synchronously. Make your unit test asynchronous as well. Also, your method signature returns a Task wrapped result, not just the result.
As a side note it is considered best practice to add the word Async
to your method name as a suffix if it returns a Task
or Task<T>
. It becomes apparent to the caller that this is an asynchronous call without having to check the return type. So GetAllCustomersAsync
instead of GetAllCustomers
.
[Fact]
public async Task GetAll_Returns_All_Customers()
{
// Arrange
var customers = new List<Customer>() { new Customer { customer_ID = 1 } };
A.CallTo(() => _repo.GetAllCustomers()).Returns(Task.FromResult(customers));
// Act
var result = await _controller.GetAll();
// Assert
Assert.Single(result);
}