简体   繁体   English

XUnit mocking 一个方法但没有返回正确的结果

[英]XUnit mocking a method but doesn't return correct result

I should be getting a list of Product Types but GetProductTypesAsync() returns a null.我应该获取产品类型列表,但GetProductTypesAsync()返回 null。

Is the class ProductTypeRepo meant to be mocked since it calls the acutal API. class ProductTypeRepo 是否意味着被嘲笑,因为它调用了实际的 API。

Anyone able to assist?任何人都可以协助?

namespace UnitTest.Service
{
  public class ProductTypeServiceTests
  {
    private readonly IServiceProvider _serviceProvider;

    private readonly Mock<IProductTypeRepo> _productTypeRepoMock;
    private readonly Mock<ILogger> _LoggerMock

    private IProductTypeService _productTypeService;
    public ProductTypeServiceTests()
    {
      _productTypeRepoMock = new Mock<IProductTypeRepo>();
      _LoggerMock= new Mock<ILogger>();
      _productTypeService = new ProductTypeService(_productTypeRepoMock.Object, _LoggerMock.Object);
    }

    [Fact]
    public async Task GetProductType_ReturnOKStatusCode()
    {
      var serviceResponse = await _productTypeService.GetProductTypesAsync();

      Assert.Equal(
          expected: serviceResponse,
          actual: serviceResponse
      );
    }
  }
}

-- --

namespace Service.ProductType
{
  public class ProductTypeService : IProductTypeService
  {
    private readonly IProductTypeRepo _repository;
    private readonly ILogger _Logger;
    public ProductTypeService(IProductTypeRepo repository, ILogger logger)
    {
      _repository = repository;
      _logger = logger;
    }

    public async Task<List<Domain.DTO.ProductTypeResponse>> GetProductTypesAsync()
    {
      var productTypes = await _repository.GetProductTypesAsync();
      if (productTypes == null)
      {
        throw new ProductTypeNotFoundException($"No Product Types were retrieved");
      }

      return productTypes;
    }      
  }
}

xxxxxxxxxx xxxxxxxx xxxxxx xxxxx xxxxxxxxxx xxxxxxxx xxxxxx xxxxx

Nowhere in the test is the mock configured to return anything when invoked.测试中没有任何地方将模拟配置为在调用时返回任何内容。

//...

[Fact]
public async Task GetProductType_ReturnOKStatusCode() {
    //Arrange
    List<Domain.DTO.ProductTypeResponse> expected = new List<Domain.DTO.ProductTypeResponse>();
    //..add items to expected list if necessary
    _productTypeRepoMock
        .Setup(_ => _.GetProductTypesAsync()) //<-- when this is invoked
        .ReturnsAsync(expected);  //<-- return something.

    //Act
    List<Domain.DTO.ProductTypeResponse> actual = await _productTypeService.GetProductTypesAsync();

    //Assert
    Assert.Equal(expected, actual);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM