I have various ViewBags which I need to test are set correctly. I am starting with testing a simple ViewBag.Title then I will move onto my other ViewBags which actually pass dynamic data.
I am trying to test this ViewBag.Title in the Create.cshtml
@{
ViewBag.Title = "Create";
}
The Booking controller for this View:
// GET: Booking/Create
public ActionResult Create()
{
return View();
}
I have tried the following:
[TestMethod]
public void BookingTest()
{
var controller = new BookingController();
var ar = controller.Create() as ViewResult;
Assert.AreEqual("Create", ar.ViewData["Title"]);
}
Also tried:
[TestMethod]
public void BookingTest()
{
var controller = new BookingController();
//var ar = controller.Create() as ViewResult;
Assert.AreEqual("Create", controller.ViewBag.Title);
}
Both unit test fail and return the following: Message: Assert.AreEqual failed. Expected:<Create>. Actual:<(null)>.
Message: Assert.AreEqual failed. Expected:<Create>. Actual:<(null)>.
Can anyone see what I am doing wrong?
Based on
@{
ViewBag.Title = "Create";
}
it would appear you are settings the ViewBag
in the actual View (ie cshtml ) file.
Based on how the Controller
and View
are separated a unit test would not have access to the rendered View. The ActionResult
( ViewResult
in this case) would be executed by the framework at runtime in order to pass the necessary data to the view.
To get the expected behavior you would have had to assign that Title
from the controller
Controller Action:
public ActionResult Create() {
ViewBag.Title = "Create";
return View();
}
for your tests to behave as expected.
[TestMethod]
public void BookingTest() {
//Arrange
var controller = new BookingController();
string expected = "Create";
//Act
var result = controller.Create() as ViewResult;
var actual = (string) result.ViewData["Title"];
//Assert
Assert.AreEqual(expected, actual);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.