避免将模拟对象传递给控制器​​ctor(单元测试)

时间:2018-07-19 12:03:11

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

假设我们在控制器方面有一些方法

    [HttpPost]
    [Produces("text/xml")]
    public async Task<IActionResult> HandleRequest([FromBody]GenericServiceRequest serviceRequest)
    {

        var authResult = await _authorizationService
                .AuthenticateAndAuthorizeAsync(new Login(serviceRequest.Login,serviceRequest.Password), serviceRequest.RequestType.ToString()).ConfigureAwait(false);

        var handler = _servicesProvider(serviceRequest.RequestType);

        try
        {
            var response = await handler.InvokeOperationAsync(serviceRequest, authResult.Provider)
            .ConfigureAwait(false);

            return new OkObjectResult(response);
        }
        catch (Exception e)
        {
            return new OkObjectResult(handler.ExceptionResult(e));
        }       
    }

在这里,我们必须为_servicesProvider和_authorizationService服务。

在测试控制器流时,我们必须创建控制器对象并传递如下设置的模拟:

    [Theory]
    [AutoDomainData]
    public async Task HandleRequestProductNotFound(
        [Frozen] Mock<Func<RequestType, IApiOperationHandler>> serviceProviderMock,
        [Frozen] Mock<IAuthenticationAuthorizationService> authorizeServiceMock)
    {
        serviceProviderMock.Setup(x => x(It.IsAny<RequestType>())).Returns(blah);

        authorizeServiceMock.Setup(x => x.AuthenticateAndAuthorizeAsync(It.IsAny<Login>(), It.IsAny<string>()))
            .ReturnsAsync(new AuthenticationAuthorizationResult(AuthenticationAuthorizationResultState.Authorized)).Verifiable();

        TopupController sut =
new TopupController(authorizeServiceMock.Object, serviceProviderMock.Object);

        // do the logic here
    }

对于每种方法,我们都执行相同的操作-创建控制器对象并传递模拟。绩效回顾并不是那么好。还有其他方法可以简化它们吗?

如果我不将它们传递给控制器​​:

[Theory]
[AutoDomainData]
public async Task HandleRequestProductNotFound(
    [Frozen] Mock<Func<RequestType, IApiOperationHandler>> serviceProviderMock,
    [Frozen] Mock<IAuthenticationAuthorizationService> authorizeServiceMock,
     TopupController sut)
{
    serviceProviderMock.Setup(x => x(It.IsAny<RequestType>())).Returns(blah);

    authorizeServiceMock.Setup(x => x.AuthenticateAndAuthorizeAsync(It.IsAny<Login>(), It.IsAny<string>()))
        .ReturnsAsync(new AuthenticationAuthorizationResult(AuthenticationAuthorizationResultState.Authorized)).Verifiable();

    var response = await sut.HandleRequest().ConfigureAwait(false);
    // do the logic here
}

然后嘲笑不锻炼,我就迷恋了。

请帮助!谢谢

0 个答案:

没有答案