Growing the application with tests

Perhaps you want to accept a parameter for one of your endpoints. Maybe you will take a visitor's name to display a friendly greeting. Let's take a look at how we might make that happen:

[TestMethod]
public void ItTakesOptionalName()
{
// Arrange
HomeController controller = new HomeController();

// Act
ViewResult result = controller.About("") as ViewResult;

// Assert
Assert.AreEqual("Your application description page.", result.ViewBag.Message);
}

We start by creating a test to allow for the About method to accept an optional string parameter. We're starting with the idea that the parameter is optional since we don't want to break any existing tests. Let's see the modified method:

public ActionResult About(string name = default(string))
{
ViewBag.Message = "Your application description page.";
return View();
}

Now, let's use the name parameter and just append it to our ViewBag.Message. Wait, not the controller. We need a new test first:

[TestMethod]
public void ItReturnsNameInMessage()
{
// Arrange
HomeController controller = new HomeController();

// Act
ViewResult result = controller.About("Fred") as ViewResult;

// Assert
Assert.AreEqual("Your application description page.Fred", result.ViewBag.Message);
}

And now we'll make this test pass:

public ActionResult About(string name = default(string))
{
ViewBag.Message = $"Your application description page.{name}";
return View();
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.29.195