我如何在核心 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);

    }

但模型状态总是正确的,我不明白为什么会发生???


我的第二次尝试在启动时在 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验证?或者如何正确检查此验证?


临摹微笑
浏览 108回答 1
1回答

慕雪6442864

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;        }
打开App,查看更多内容
随时随地看视频慕课网APP