How can I get a model from ViewResult in asp.net mvc unittest?

I invoke a controller action in unit test.

 ViewResult result = c.Index(null,null) as ViewResult;

I passed the result to ViewResult because this is what I return to the controller:

return View(model);

But how can I access this model variable in my unit test?

+4
source share
2 answers
// Arrange
var c = new MyController();

//Act
var result = c.Index(null,null);
var model = result.ViewData.Model; 

//Assert
Assert("model is what you want");
+9
source

I would recommend you an excellent MVContrib test helper . Your test might look like this:

[TestMethod]
public void SomeTest()
{
    // arrange
    var p1 = "foo";
    var p2 = "bar";

    // act
    var actual = controller.Index(p1, p2);

    // assert
    actual
        .AssertViewRendered() // make sure the right view has been returned
        .WithViewData<SomeViewData>(); // make sure the view data is of correct type
}

You can also claim model properties

actual
    .AssertViewRendered()
    .WithViewData<SomeViewData>()
    .SomeProp
    .ShouldEqual("some expected value");
+4
source

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


All Articles