我使用xUnit编写了单元测试,以测试我的ASP.net核心Web API控制器中的方法。
public class RegistrationsControllerTest : ControllerTestBase<RegistrationsController>
{
RegistrationsController registrationsController;
public RegistrationsControllerTest()
{
registrationsController = new RegistrationsController(log, registrationRepository);
}
[Fact]
public void Add_InvalidObjectPassed_ReturnsBadRequest()
{
// Arrange
var postBackMissingItem = new RegistrationFilter()
{
Id = Guid.NewGuid().ToString(),
PostbackURI = "https://test.example.com",
FailureURI = "https://testfail.example.com"
};
postBackMissingItem.PostbackURI = null;
// Act
var badResponse = registrationsController.AddRegistration(postBackMissingItem);
// Assert
Assert.IsType<BadRequestObjectResult>(badResponse);
}
}
我正在尝试在控制器方法中使用TryValidateModel
来验证输入。
public class RegistrationsController : ControllerBase
{
ILogger<RegistrationsController> log;
IRegistrationRepository registrationRepository;
public RegistrationsController(ILogger<RegistrationsController> log, IRegistrationRepository registrationRepository)
{
this.log = log;
this.registrationRepository = registrationRepository;
RegistrationsController regController = new RegistrationsController(this.log, this.registrationRepository);
regController.ControllerContext = new ControllerContext();
}
[HttpPost(Name = nameof(AddRegistration))]
public async Task<IActionResult> AddRegistration([FromBody] RegistrationFilter registrationRequest)
{
// Ensure Id=null for inserts
registrationRequest.Id = null;
// Validate request content
if (!TryValidateModel(registrationRequest))
{
var errorText = "BadRequest. ModelState invalid";
log.ErrorEx(tr => tr.SetObject(new { Registration = registrationRequest }, errorText));
return BadRequest(ModelState);
}
// Some code
}
}
当我调试单元测试时,它在具有TryValidateModel
的行上引发错误。
错误是对象引用未设置为对象的实例。我在Stack Overflow上遇到了类似的问题,他们提到了模拟TryValidateModel
,但我不想对其进行模拟。
在此问题How do I Unit Test Actions without Mocking that use UpdateModel?中,有人提到将默认控制器上下文添加到控制器。
我尝试了这种方法,但是在尝试调试测试和错误时退出了调试模式
程序“ [25720] dotnet.exe”已退出,代码为-1073741819(0xc0000005)访问冲突
显示在输出窗口中。
在控制器方法构造函数中,我添加了ControllerContext行,但是调试模式因我提到的错误而退出。
我是否添加错误或在错误的地方?通过我的单元测试应该做什么修改?