我尝试为我的 API 控制器方法创建测试。简单来说,我写了add方法。
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> AddAsync([FromBody]BaseUserDTO dto)
{
if (ModelState.IsValid)
{
return Ok();
}
else
{
return ValidationProblem();
}
}
在 dto 模型中我有
public class BaseUserDTO
{
[Required(ErrorMessage = "This field should be filled in", AllowEmptyStrings = false)]
[RegularExpression(@"(^[a-zA-Z0-9_ -]+$)", ErrorMessage = ("Use only Latin characters"))]
public string FirstName { get; set; }
[Required(ErrorMessage = "This field should be filled in", AllowEmptyStrings = false)]
[RegularExpression(@"(^[a-zA-Z0-9_ -]+$)", ErrorMessage = ("Use only Latin characters"))]
public string LastName { get; set; }
}
我写了第一个尝试测试数据注释
[Fact]
public async Task UserValidationError()
{
//Arrange
BaseUserDTO userDTO = new BaseUserDTO
{
FirstName = "222A@@@",
LastName = "Test",
Email = "Test@test.com",
PhoneNumber = "(111)111-1111",
Role = 0,
Password = "1234567A",
RetypePassword = "1234567A"
};
UserController controller = new UserController(userServicesMock.Object, mapperMock.Object, loggerMock.Object);
//Act
IActionResult result = await controller.AddAsync(userDTO);
//Assert
Assert.IsType<BadRequestObjectResult>(result);
}
但模型状态总是正确的,我不明白为什么会发生???
我的第二次尝试在启动时在 mongo 连接中获取 NullReference startup(在正常情况下它工作良好(当应用程序工作时),由邮递员检查)
[Fact]
public async Task UserValidationError(string userState)
{
//Arrange
BaseUserDTO userDTO = new BaseUserDTO
{
FirstName = "222A@@@",
LastName = "Test",
Email = "Test@test.com",
PhoneNumber = "(111)111-1111",
Role = 0,
Password = "1234567A",
RetypePassword = "1234567A"
};
}
通常如何创建单元测试来检查DataAnnotation验证?或者如何正确检查此验证?
慕雪6442864
相关分类