Testing a controller in asp.net mvc

I would like to check the validation provided by the DTO. This is the head of the bone of the controller creating the action:

[AcceptVerbs(HttpVerbs.Post)]
        public RedirectToRouteResult Create(SomeDTO SomeDTO)
        {
            SomeObject SomeObject = null;

            try
            {
SomeObject = this.RepositoryService.getSomeObjectRepository().Create(SomeDTO, this.RepositoryService);
            }
            catch (BrokenRulesException ex)
            {
                ex.AddModelStateErrors(ModelState, "Model");
            }
            catch (Exception e)
            {
                ModelState.AddModelError("Exception", e.Message);
            }

            TempData["ViewData"] = ViewData;
            TempData["SomeDTO "] = SomeDTO;

            return ModelState.IsValid ? RedirectToAction("SomeObjectDetail", new { Id = SomeObject.Id }) : RedirectToAction("Form");
        }

The mechanics, although not relevant, are as follows: I have a strongly typed view = form that sends dto to this action, which either returns a form or the details page of the created object.

I would like to unit test to indicate if the model contains certain key / errorMessage combinations with some invalid dto. Has anyone done similar things? Any pointers would be greatly appreciated.

Thank.

Regards,

Christian

0
source share
1 answer

, , . , , / , , . , /, , DataAnnotations, , . Microsoft .

, () ViewResult

, - .

[TestMethod]
public void TestCreate()
{
     // set up

    var result = Create( invalidDTO ) as ViewResult;

    var modelState = result.ViewData.ModelState;

    Assert.IsFalse( modelState.IsValid );

    var errors = modelState.Errors;

    Assert.AreEqual( 1, errors.Count );
    Assert.AreEqual( errors[0].ErrorMessage, "some error message" );
}
+1

Source: https://habr.com/ru/post/1746209/


All Articles