我如何在核心网络 api 中测试我的数据注释字段?

how i can test my data annotation field in core web api?

我尝试为我的 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);
    }

但模型状态始终为真,我不明白为什么会这样????

我第二次尝试在 startup 启动时在 mongo 连接中获取 NullReference(在正常情况下它工作正常(当应用程序工作时),通过邮递员检查)

[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"
        };

        var b = new WebHostBuilder().UseStartup<Startup>().UseEnvironment("development");

        var server = new TestServer(b) { BaseAddress = new Uri(@"http://localhost:54133") };
        var client = server.CreateClient();
        var json = JsonConvert.SerializeObject(userDTO);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        UserController controller = new UserController(userServicesMock.Object, mapperMock.Object, loggerMock.Object);

        //Act
        var result = await client.PostAsync("api/User", content);

        //assert
        Assert.Equal(400, (int)result.StatusCode);
    }

通常如何创建单元测试来检查 DataAnnotation 验证?或者如何正确检查这个验证?

using System.ComponentModel.DataAnnotations;
/*other using*/

[Fact]
public void UserValidationError()
{
    //Arrange
    BaseUserDTO userDTO = new BaseUserDTO
    {
       FirstName = "222A@@@",
       LastName = "Test",
       Email = "Test@test.com",
       PhoneNumber = "(111)111-1111",
       Role = 0,
       Password = "1234567A",
       RetypePassword = "1234567A"
    };

    //ACT
    var lstErrors = ValidateModel(userDTO);

    //ASSERT
    Assert.IsTrue(lstErrors.Count == 1);   
    //Or 
    Assert.IsTrue(lstErrors.Where(x => x.ErrorMessage.Contains("Use only Latin characters")).Count() > 0);
}

//
        private IList<ValidationResult> ValidateModel(object model)
        {
            var validationResults = new List<ValidationResult>();
            var ctx = new ValidationContext(model, null, null);
            Validator.TryValidateObject(model, ctx, validationResults, true);
            return validationResults;
        }

Microsoft 站点中的更多详细信息:https://docs.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/unit-testing-controllers-in-web-api