4 Mayıs 2015 Pazartesi

Mock ModelState

This may be a silly example, but hopefully it moves the discussion forward:
The following code is in my Controller Action: 
if (ViewData.ModelState.Count > 10)
{
ViewData["Message"] = "Too many errors to continue";return View();
}
Here is a test with mocking and a test wtihout mocking:
[Test]public void Test11ModelStateErrorsWithMock()
{
HomeController homeController = new HomeController();

MockRepository mockRepository = new MockRepository();
ModelStateDictionary mockModelStateDictionary = (ModelStateDictionary)mockRepository.DynamicMock(typeof(ModelStateDictionary));
homeController.ViewData.ModelState = mockModelStateDictionary;
Expect.Call(mockModelStateDictionary.Count).Return(11);
mockRepository.ReplayAll();
ViewResult viewResult = (ViewResult)homeController.About();
mockRepository.VerifyAll();
Assert.AreEqual("Too many errors to continue", viewResult.ViewData["Message"]);
}
[Test]public void Test11ModelStateErrorsWithoutMock()
{
HomeController homeController = new HomeController();
homeController.ViewData.ModelState.AddModelError("1""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("2""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("3""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("4""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("5""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("6""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("7""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("8""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("9""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("10""FakeValue""FakeException");
homeController.ViewData.ModelState.AddModelError("11""FakeValue""FakeException");
ViewResult viewResult = (ViewResult)homeController.About();
Assert.AreEqual("Too many errors to continue", viewResult.ViewData["Message"]);
}

In my opinion, the test with the mock is less verbose and shows the intent better.  It is easier to change (for example if the requirement changed to having a limit of 20 errors).

Hiç yorum yok:

Yorum Gönder

.net 6 mapget kullanımı

 app.UseEndpoints(endpoints => {     endpoints.MapGet("/", async context =>     {         var response = JsonConvert.Seriali...