为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
临摹微笑 2023-09-24 11:40:23
我尝试为我的 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验证?或者如何正确检查此验证?
查看完整描述

1 回答

?
慕雪6442864

TA贡献1812条经验 获得超5个赞

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);

}


//http://stackoverflow.com/questions/2167811/unit-testing-asp-net-dataannotations-validation

        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;

        }

查看完整回答
反对 回复 2023-09-24
  • 1 回答
  • 0 关注
  • 107 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信