Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to unit test ASP.NET MVC ViewBag properties set in the view?

Tags:

Say I have a view with the following code at the top of the page:

@{     ViewBag.Title = "About Us";     Layout = "~/Views/Shared/_Layout.cshtml"; } 

And I have a controller method:

    public ActionResult About()     {         return View();     } 

How can I test that the ViewBag was set properly?

I have tried the following code.

[TestCase] public void About() {     var controller = new AboutController();     var ar = controller.About() as ViewResult;     Assert.AreEqual("About Us", ar.ViewBag.Title); } 

But I get the following result when I run the test:

Tests.Controllers.AboutControllerTests.About():     Expected: "About Us"     But was: null 
like image 659
Jim Avatar asked Jan 11 '11 19:01

Jim


People also ask

Can ViewData be accessed via the View Bag property?

To pass the strongly typed data from Controller to View using ViewBag, we have to make a model class then populate its properties with some data and then pass that data to ViewBag with the help of a property. And then in the View, we can access the data of model class by using ViewBag with the pre-defined property.

Can we pass ViewBag from view to controller?

ViewBag itself cannot be used to send data from View to Controller and hence we need to make use of Form and Hidden Field in order to pass data from View to Controller in ASP.Net MVC Razor.

What if the ViewBag property name matches with the key of ViewData?

It will throw a runtime exception, if the ViewBag property name matches with the key of ViewData.

What is ViewData in razor?

ViewData is a container for data to be passed from the PageModel to the content page. ViewData is a dictionary of objects with a string-based key. You add items to ViewData as follows: public class IndexModel : PageModel.


2 Answers

Since both the ViewData and ViewBag use the same storage pattern, you should be able to use ViewData[yourKey] in your tests.

So your test will look like this:

[TestCase] public void About() {     var controller = new AboutController();     var ar = controller.About() as ViewResult;     Assert.AreEqual("About Us", ar.ViewData["Title"]); } 
like image 112
Phil.Wheeler Avatar answered Oct 24 '22 09:10

Phil.Wheeler


Have you tried

Assert.AreEqual("About Us", controller.ViewBag.Title); 

It works for me

like image 22
Gigapr Avatar answered Oct 24 '22 08:10

Gigapr