Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check Model properties in unit test

I have a Action as bellow:

public ActionResult SaveAndExit()
{
    ViewModel1 viewModel = new ViewModel1();

    return View("Index", viewModel);
}

In Unit Test I want to check if view Reg in viewModel is null or not. any suggestions please

Test:

//act
var result = controller.SaveAndExit(viewModel) as ViewResult;

//assert
//Assert.IsNotNull(!result.Model["Reg"].Equals(null));
like image 288
user1211185 Avatar asked Dec 26 '22 22:12

user1211185


2 Answers

I would tend to write the asserts as follows (using Microsoft test framework asserts here - you didn't specify nunit):

// Act
ActionResult result = controller.SaveAndExit(viewModel);

// Assert
Assert.IsInstanceOfType(result, typeof(ViewResult));
ViewResult viewResult = (ViewResult)result;

Assert.IsInstanceOfType(viewResult.Model, typeof(ViewModel1));
ViewModel1 model = (ViewModel1)viewResult.Model;

Assert.IsNotNull(model.Reg);
like image 137
magritte Avatar answered Jan 10 '23 06:01

magritte


Unit tests should test business logic. You don't need to write a unit test just for checking some property for null.

like image 35
Alex Kovanev Avatar answered Jan 10 '23 06:01

Alex Kovanev