Pseudorandom Knowledge

Testing the view

The view part of ASP.NET MVC is difficult to test in isolation. It is more commonly integration tested together with the rest of the system.

@model IEnumerable<ShipRegister.Models.Ship>
<!DOCTYPE html>
 
<html>
<head>
    <title>Ship register</title>
    <script src="~/Scripts/jquery-2.1.1.js"></script>
    <script>
        $(function () {
            $("li").on("click", function () {
                $(this).css("color", "red");
            });
        });
    </script>
</head>
<body>
    <h2>Ships</h2>
    <ul>
    @foreach (Ship ship in Model) {
        <li>@ship.Name</li>
    }
    </ul>
 
    <form action="/Ship/Create" method="post">
        <input type="text" name="Name" placeholder="Ship name" />
        <input type="submit" id="Button" value="Add" />
    </form>
</body>
</html>

The view also includes JavaScript which may be tested at the same time.

[TestClass]
public class ShipViewTests
{
    [TestMethod]
    public void WebRootShowsShipRegister()
    {
        using (IWebDriver driver = new FirefoxDriver())
        {
            // Arrange / Act
            driver.Navigate().GoToUrl("http://localhost:51794/");
 
            // Assert
            Assert.AreEqual("Ship register", driver.Title);
        }
    }
 
    [TestMethod]
    public void SubmitNewShipShowsNewShip()
    {
        string shipName = "Ship " + Guid.NewGuid();
 
        using (IWebDriver driver = new FirefoxDriver())
        {
            // Arrange
            driver.Navigate().GoToUrl("http://localhost:51794/");
            IWebElement textInput = driver.FindElement(By.Name("Name"));
            IWebElement submitButton = driver.FindElement(By.Id("Button"));
 
            // Act
            textInput.SendKeys(shipName);
            submitButton.Click();
 
            // Assert
            IWebElement ship = driver.FindElements(By.TagName("li")).Last();
            Assert.AreEqual(shipName, ship.Text);
        }
    }
 
    [TestMethod]
    public void ClickShipColorsShipRed()
    {
        using (IWebDriver driver = new FirefoxDriver())
        {
            // Arrange
            driver.Navigate().GoToUrl("http://localhost:51794/");
            IWebElement ship = driver.FindElements(By.TagName("li")).First();
 
            // Act
            ship.Click();
 
            // Assert
            Assert.AreEqual("color: red;", ship.GetAttribute("style"));
        }
    }
}

These tests are performed in Firefox with the help of Selenium. A new Firefox instance is opened for each test.