D
D
DD-var2021-06-25 18:51:21
ASP.NET
DD-var, 2021-06-25 18:51:21

Why doesn't validation work when testing a controller?

there is a controller for creating a new user, a model should come into it. I send an empty model through the test and no error comes out. if you add it manually, then everything is triggered by the
controller:

public async Task<ActionResult> Create([FromBody]RegisterViewModel user)
        {
           // ModelState.AddModelError("swe","ssssss");
  
            if (ModelState.IsValid)
            {
                var result = await _userService.Create(user);
                return Ok(user);
            }

            else
            {
                return BadRequest(ModelState);
            }
        }

model:
public class RegisterViewModel
    {
        //обязательные поля
        [Required(ErrorMessage = "Пустое поле")]
        public string FirstName { get; set; }


        [Required(ErrorMessage = "Пустое поле")]
        public string FullName { get; set; }


        [Required(ErrorMessage = "Пустое поле")]
        public string UserName { get; set; }

}


test:
public void CheckAddUser()
        {
            RegisterViewModel fakeUser = new RegisterViewModel();
            
            fakeUser.Password = null;
            fakeUser.UserName = null;
            fakeUser.Email = null;
            
            
            var moc = new Mock<IUserService>();
            moc.Setup(c => c.Create(It.IsAny<RegisterViewModel>()) );
            

            var userController = new TestController(moc.Object);

            var result = userController.Create(fakeUser);
//должен вернуть ошибку
          //  Assert.IsInstanceOf(result.GetType(),typeof(BadRequestResult));
            Assert.AreSame(result,typeof(BadRequestResult));
          

        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2021-06-27
@DD-var

Most likely, asp does the validation, not the controller, and when creating the controller, it passes the ModelState to it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question