使用Moq的服务模拟异步方法

时间:2017-09-18 10:17:42

标签: c# unit-testing asp.net-core moq mstest

我在.Net Core API中工作。我希望对GetArtists上的ArtistsController方法进行单元测试。

CODE

这是我的控制器代码:

[Route("artists")]
public class ArtistsController : Controller
{
  private readonly IPermissionsService _permissionsService;
  private readonly IArtistsService _artistsService;
  private readonly ILogger<ArtistsController> _logger;

  public ArtistsController(IPermissionsService permissionsService, IArtistsService artistsService, ILogger<ArtistsController> logger)
  {
    _permissionsService = permissionsService ?? throw new ArgumentNullException(nameof(permissionsService));
    _artistsService = artistsService ?? throw new ArgumentNullException(nameof(artistsService));
    _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  }

  [HttpGet]
  public async Task<IActionResult> GetArtists()
  {
    var permissions = await _permissionsService.GetPermissionsAsync(HttpContext);
    var artists = _artistsService.GetAllArtists(permissions.UserId, permissions.IsAdministrator);
    return Ok( new { artists });
  }
}

这是我写的测试方法:

[TestClass]
public class ArtistsControllerTests
{
  private readonly Mock<IPermissionsService> _mockPermissionsService = new Mock<IPermissionsService>();
  private readonly Mock<IArtistsService> _mockArtistsService = new Mock<IArtistsService>();
  private readonly Mock<ILogger<ArtistsController>> _mockLogger = new Mock<ILogger<ArtistsController>>();

  public void Setup()
  {
    _mockArtistsService.Reset();
    _mockPermissionsService
      .Setup(service => service.GetPermissionsAsync(It.IsAny<HttpContext>()))
      .Returns(Task.FromResult(new Permissions { UserId = "112233", IsAdministrator = false }));
    _mockArtistsService.Setup(service => service.GetAllArtists(It.IsAny<string>(), false)).Returns(new ArtistCardDtoCollection());
  }

  [TestMethod]
  public async Task GetArtists_ReturnsOKStatusCode()
  {
    // arrange
    var artistsController = new ArtistsController(_mockPermissionsService.Object, _mockArtistsService.Object, _mockLogger.Object);
    // act
    var getArtistsResult = await artistsController.GetArtists();
    var okResult = getArtistsResult as OkObjectResult;
    // assert
    Assert.IsInstanceOfType(okResult, typeof(OkObjectResult));
  }
}

以下是IPermissionsServicePermissions类。

public interface IPermissionsService
{
  Task<Permissions> GetPermissionsAsync(HttpContext httpContext);
}

public class Permissions
{
  public string UserId { get; set; }
  public bool IsAdministrator { get; set; }
}

当我运行时,我收到以下错误:

  

Project.ArtistsControllerTests.GetArtists_ReturnsOKStatusCode抛出异常:   System.NullReferenceException:未将对象引用设置为对象的实例。

调试时,我发现var permissions = await _permissionsService.GetPermissionsAsync(HttpContext);会返回null

我必须对我嘲笑的方式有疑问:

_mockPermissionsService
    .Setup(service => service.GetPermissionsAsync(It.IsAny<HttpContext>()))

为什么不进行上述工作?

1 个答案:

答案 0 :(得分:2)

[TestInitilize]未被调用,因此在执行测试之前未设置模拟。

因此,当执行测试时,它们将返回null。

您的设置代码是正确的,它只是没有被调用。

[TestInitialize] public void Setup() { _mockArtistsService.Reset(); _mockPermissionsService .Setup(service => service.GetPermissionsAsync(It.IsAny<HttpContext>())) .Returns(Task.FromResult(new Permissions { UserId = "112233", IsAdministrator = false })); _mockArtistsService.Setup(service => service.GetAllArtists(It.IsAny<string>(), false)).Returns(new ArtistCardDtoCollection()); } 方法更改为构造函数

[TestMethod]
public async Task GetArtists_ReturnsOKStatusCode() {
    // arrange
    _mockArtistsService.Reset();
    _mockPermissionsService
      .Setup(service => service.GetPermissionsAsync(It.IsAny<HttpContext>()))
      .Returns(Task.FromResult(new Permissions { UserId = "112233", IsAdministrator = false }));
    _mockArtistsService.Setup(service => service.GetAllArtists(It.IsAny<string>(), false)).Returns(new ArtistCardDtoCollection());
    var artistsController = new ArtistsController(_mockPermissionsService.Object, _mockArtistsService.Object, _mockLogger.Object);
    // act
    var getArtistsResult = await artistsController.GetArtists();
    var okResult = getArtistsResult as OkObjectResult;
    // assert
    Assert.IsInstanceOfType(okResult, typeof(OkObjectResult));
}

或使用fileFilter属性

装饰方法
multer({
    fileFilter: function (req, file, cb) {
        if (file.mimetype !== 'application/pdf') {
            req.fileValidationError = 'Only PDF files can be uploaded';
            return cb(null, false, new Error('Only PDF files can be uploaded'));
        }
        cb(null, true);
    }
});

或者只是将排列移入测试本身

limits