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
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.
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.
It will throw a runtime exception, if the ViewBag property name matches with the key of ViewData.
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.
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"]); }
Have you tried
Assert.AreEqual("About Us", controller.ViewBag.Title);
It works for me
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With