我有一个API,我打算在其上通过xUnit和Moq进行单元测试.它实际上有一个构造函数,但我不得不添加另一个构造函数,以根据Visual Studio的建议进行特定的测试.它非常适合测试,但在try 通过Swagger测试API时,我遇到了另一个错误. "System.InvalidOperationException: Multiple constructors accepting all given argument types have been found in type 'Product.API.Controllers.ProductController'. There should only be one applicable constructor". 下面是控制器的内容
public class ProductController : ControllerBase
{
private readonly IMediator _mediator;
private readonly IConfiguration _configuration;
private readonly UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
private readonly ProductDbContext _productDbContext;
private readonly IUserService _userService;
public ProductController(IConfiguration configuration, UserManager<User> userManager, ProductDbContext productDbContext
, SignInManager<User> signInManager, IUserService userService)
{
_configuration = configuration;
_userManager = userManager;
_productDbContext = productDbContext;
_signInManager = signInManager;
_userService = userService;
}
public ProductController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> GetAllProducts()
{
var products = await _mediator.Send(new GetAllProductsQuery());
return Ok(products);
}
以下是单元测试的代码
private readonly Mock<IMediator> _mediatorMock;
private readonly ProductController _controller;
public ProductControllerTest()
{
_mediatorMock = new Mock<IMediator>();
_controller = new ProductController(_mediatorMock.Object);
}
[Fact]
public async Task ProductController_GetAllProducts_ShouldReturnStatusCode200()
{
//arrange
var expected = new List<ProductModelDTO>();
_mediatorMock.Setup(m=> m.Send(It.IsAny<GetAllProductsQuery>(), default(CancellationToken))).ReturnsAsync(expected);
//act
var result = await _controller.GetAllProducts();
//assert
var okResult = result as OkObjectResult;
okResult?.StatusCode.Should().Be(200);
okResult?.Value.Should().BeOfType<List<ProductModelDTO>>();
}
我遇到了一个可能的解决方案;向第二个构造函数添加一个[FromServices].但我也犯了同样的错误!