我正在尝试使用xUnit
测试我的控制器,但是在执行Customer Controller时出现以下错误:
“以下构造函数参数没有匹配的灯具 数据:CustomerController customerController”
测试课程
public class UnitTest1
{
CustomerController _customerController;
public UnitTest1(CustomerController customerController)
{
_customerController = customerController;
}
[Fact]
public void PostTestSuccessful()
{
Guid guid = Guid.NewGuid();
CustomerViewModel model = new CustomerViewModel()
{
Id = guid,
Name = "testName",
Email = "test email",
PhoneNumber = "test phone",
Address = "test address",
City = "test city",
Gender = "Male"
};
var actionResult = _customerController.Post(model);
Assert.NotNull(actionResult);
Assert.IsType<Task<IActionResult>>(actionResult);
Assert.True(actionResult.IsCompletedSuccessfully);
}
CustomerController类
[Route("customers")]
public class CustomerController : ControllerBase
{
private readonly ILogger _logger;
private readonly ICustomerService _customerService;
public CustomerController(ILogger<CustomerController> logger,
ICustomerService customerService)
{
_logger = logger;
_customerService = customerService;
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] CustomerViewModel viewModel)
{
var customerToBeSaved = viewModel.Adapt<CustomerServiceModel>();
var customer = await _customerService.SaveAsync(customerToBeSaved);
var result = customer.Adapt<CustomerViewModel>();
return Ok(result);
}
答案 0 :(得分:3)
对于测试框架,您需要模拟库以通过DI将模拟对象注入测试类中。您可以使用Nmock,Moq或任何其他模拟库来设置构造函数注入。
https://www.c-sharpcorner.com/uploadfile/john_charles/mocking-in-net-with-moq/
答案 1 :(得分:1)
如果您不想使用任何模拟框架,只需在构造函数中新建CustomerController。
答案 2 :(得分:0)
本文显示了如何使xunit与.Net Core ASP.Net很好地协同工作。它实际上替代了启动,因此您的控制器可以在同一进程中运行,并且可以像在本地一样测试它们。
https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2
答案 3 :(得分:0)
您缺少的是测试类的 IClassFixture 接口。这将解决问题...
public class UnitTest1 : IClassFixture<CustomerController>