4.3. Solution

Let's take a look at the implementations of the above design that will address the problems at hand. My objective was to simplify the code and make it elegant. Here is one of my tests before any changes:

[Test]
public void Login_Should_Return_Error_If_Username_Is_Missing()
{
    var mockProvider = new Mock<MembershipProvider>();
    var mockAuthentication = new Mock<IFormsAuthentication>();
    var ac = new AccountController(mockAuthentication.Object,
                                   mockProvider.Object);
    var results = ac.Login(string.Empty, password, true);

    var errormessage = "Username is required";
var errorKey = "username";

    Assert.IsNotNull(results);
    Assert.IsInstanceOfType(typeof(ViewResult), results);
    ac.ViewData.ModelState.AssertErrorMessage(errorKey, errormessage);
    Assert.IsInstanceOfType(typeof(LoginModel),
                            ((ViewResult)results).ViewData.Model);

    var model = (((ViewResult)results).ViewData.Model as LoginModel);

    Assert.AreEqual(string.Empty, model.Username);
    Assert.AreEqual(password, model.Password);
    Assert.AreEqual(true, model.RememberMe);
    Assert.AreEqual("Login", ac.ViewData["Title"], "Page title is wrong");
}

On its own, the above test looks good and doesn't need much refactoring. But the fact that many of the above lines were repeated in other tests gave rise to the need to refactor. To start with, my assertions are very generic and will be called by other methods. These lines can be moved into a method:

Assert.IsNotNull(results); Assert.IsInstanceOfType(typeof(ViewResult), results); ac.ViewData.ModelState.AssertErrorMessage(errorKey, ...

Get ASP.NET MVC 1.0 Test Driven Development: Problem - Design - Solution now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.