简体   繁体   English

Controller 在运行 xUnit 测试时返回 null IActionResult

[英]Controller returns a null IActionResult when running xUnit test

I'm having some difficulties making my unit test pass.我在通过单元测试时遇到了一些困难。

This is my unit test class:这是我的单元测试 class:

[Collection(nameof(VehicleControllerCollection))]
public class DetectVin
{
    private readonly VehicleControllerFixture _controllerFixture;

    public DetectVin(VehicleControllerFixture controllerFixture)
    {
        _controllerFixture = controllerFixture;
    }

    [Fact]
    public async Task ReturnsBadRequestGivenPictureIsNull()
    {
        var controllerMock = _controllerFixture.VehicleController;
        controllerMock.Protected().Setup<bool>("HasAnyLicenseClaims", ItExpr.IsAny<string[]>()).Returns(true);
        var result = await controllerMock.Object.DetectVin(null, 1) as BadRequestResult;

        result.Should().NotBeNull();
    }
}

It is using a CollectionFixture that looks like this:它使用如下所示的CollectionFixture

public class VehicleControllerFixture
{
    public Mock<v1.v1._0.Vehicle.VehicleController> VehicleController { get; set; }

    public VehicleControllerFixture()
    {
        var vehicleServiceMock = new Mock<IVehicleService>();
        VehicleController = new Mock<v1.v1._0.Vehicle.VehicleController>(vehicleServiceMock.Object);
    }
}

[CollectionDefinition(nameof(VehicleControllerCollection))]
public class VehicleControllerCollection : ICollectionFixture<VehicleControllerFixture>
{
}

And the method that's being test DetectVin looks like this:正在测试DetectVin的方法如下所示:

[RequestSizeLimit(5242880)]
[HttpPost]
public async Task<IActionResult> DetectVin([FromBody]string picture, [FromQuery]int activityId)
{
    if (!HasAnyLicenseClaims("ModuleMyWorkshopHGSService", "ModuleMyWorkshopToyotaService")) { return NotAllowed(); }

    if (string.IsNullOrWhiteSpace(picture))
    {
        return BadRequest();
    }

    var result = await _vehicleService.DetectVin(picture);
        
    if (string.IsNullOrWhiteSpace(result))
    {
        return UnprocessableEntity();
    }

    var activityVinDetection = new ActivityVinDetection
    {
        ActivityId = activityId,
        UsedOnActivity = false,
        Vin = result
    };

    _vehicleService.InsertActivityVinDetection(activityVinDetection);

    return Ok(result);
}

My problem is that the DetectVin method always returns null .我的问题是DetectVin方法总是返回null This is even though I can debug the test and step through the method just fine, seeing that it actually returns the BadRequest() .即使我可以很好地调试测试并单步执行该方法,看到它实际上返回BadRequest()也是如此。

Anyone has any idea why that could be?任何人都知道为什么会这样?

EDIT:编辑:

Here is the base controller that the VehicleController inherits from:这是VehicleController继承自的基数 controller:

public abstract class AIdpClaimsAuthController : BaseController, IAuthorizedController
{
    public int WorkshopId
    {
        get
        {
            var wid = User.Claims.SingleOrDefault(sd => sd.Type == "sub");
            if (wid == null || !int.TryParse(wid.Value, out int workshopId))
            {
                throw new System.Security.Authentication.AuthenticationException("Unauthorized");
            }
            return workshopId;
        }
    }
        
    protected virtual bool HasAnyLicenseClaims(params string[] licenseClaims)
    {
        foreach (var claim in licenseClaims)
        {
            if (AuthorizationService.HasLicenseClaims(WorkshopId, claim))
            {
                return true;
            }
        }
        return false;
    }
}

And here is the base controller that the AIdpClaimsAuthController inherits from:这是AIdpClaimsAuthController继承自的基数 controller:

public abstract class BaseController : Controller
{
    private IAuthorizationService __authorizationService;
    public IAuthorizationService AuthorizationService
    {
        get
        {
            if (__authorizationService == null)
            {
                __authorizationService = this.HttpContext.RequestServices.GetService(typeof(IAuthorizationService)) as IAuthorizationService;
            }
            return __authorizationService;
        }
    }
}

Found the solution using MockBehaviour.Strict .使用MockBehaviour.Strict找到解决方案。 Turns out that I also needed to mock the result that my controller generated for the BadRequest method.事实证明,我还需要模拟 controller 为BadRequest方法生成的结果。

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

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