Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error while testing my async function using XUNIT in c# .net core

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.Task1[System.Collections.Generic.List1[WebAPI__CodeFirst.Classes.Customer]]’ to type ‘System.Collections.Generic.IEnumerable`1[WebAPI__CodeFirst.Classes.Customer]’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading