Home > Enterprise >  How to mock which return type is 'async Task<(IList<object>, PaginationModel)>'
How to mock which return type is 'async Task<(IList<object>, PaginationModel)>'

Time:04-26

My method is

public async Task<IActionResult> GetLicensePath([FromBody] PathSearch pathSearch)
{
    var (paths, pagination) = await _pathService.GetJobPathByFilters(pathSearch); //need to mock this line.
    return ok(new OkResponse<IList<JobLicensePath>>(licensePaths, pagination.PageNumber, pagination.PageSize, pagination.TotalPages, pagination.TotalCount));
}

my service class method returning as well

public async Task<(IList<JobLicensePath>, PaginationModel)> GetJobPathByFilters(PathSearch pathSearch)
{
    //...
    IEnumerable<JobLicensePath> objJobLicensePath = null;
    objJobLicensePath = await _baseRepository.GetAsync<JobLicensePath>(filter: expression, null, null, skip: skipVal, take: take, false);
    return (objJobPath.ToList(), new PaginationModel(pageNumber, pageSize, totalCount));
}

I am trying to mock like below few trials but which all are not setup.

First Try

mockIJobLicensePathService
   .Setup(x => x.GetJobPathByFilters(It.IsAny<PathSearch>()))
   .Returns(Task.FromResult(It.IsAny<Task(IList<JobLicensePath>, PaginationModel)>()));

The type arguments for method 'Task.FromResult(TResult)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Second Try

mockIJobLicensePathService
    .Setup(x => x.GetJobPathByFilters(It.IsAny<PathSearch>()))
    .Returns(Task.FromResult(It.IsAny<IList<JobLicensePath>, PaginationModel>()>));

Using the generic method 'It.IsAny()' requires 1 type arguments

mockIJobLicensePathService
   .Setup(x => x.GetJobPathByFilters(It.IsAny<PathSearch>()))
   .Returns(Task.FromResult(It.IsAny<IList<JobLicensePath>>(), It.IsAny<PaginationModel>()));

No overload for method 'FromResult' takes 2 arguments

CodePudding user response:

It.IsAny is used to check the method's parameter. You can mock it like this:

// arrange
(IList<JobLicensePath>, PaginationModel) result = (new List<JobLicensePath>(), new PaginationModel());
var mock = new Mock<IPathService>();
mock
    .Setup(s => s.GetJobPathByFilters(It.IsAny<PathSearch>()))
    .Returns(Task.FromResult(result));

CodePudding user response:

You should use ReturnsAsync method of Moq as shown below.

// arrange

// Create the dummy object or use the existing one if already exists as part of your mock setup.
PathSearch pathSearch = new PathSearch();


mockIJobLicensePathService
      .Setup(x => x.GetJobPathByFilters(It.IsAny<PathSearch>()))
      .ReturnsAsync(pathSearch);
  • Related