Testing the controller

The controller is the most straightforward part of ASP.NET MVC to test.

public class ShipController : Controller
{
    private readonly IShipRepository Repository;

    public ShipController() : this(new ShipRepository()) { }

    public ShipController(IShipRepository repository)
    {
        Repository = repository;
    }

    public ViewResult Index()
    {
        IEnumerable<Ship> ships = Repository.GetList();
        return View(ships);
    }

    public RedirectResult Create(Ship ship)
    {
        if (ModelState.IsValid)
        {
            Repository.Insert(ship);
        }
        return Redirect("/");
    }
}

The only thing this controller depends on is the repository which handles the model.

[TestClass]
public class ShipControllerTests
{
    [TestMethod]
    public void IndexReturnsAllShips()
    {
        var ships = new List<Ship>
            {
                new Ship { Name = "Ship 1"},
                new Ship { Name = "Ship 2"}
            };

        // Arrange
        var repository = Mock.Of<IShipRepository>(r => r.GetList() == ships);
        var controller = new ShipController(repository);

        // Act
        ViewResult result = controller.Index();

        // Assert
        Assert.AreEqual(ships, result.Model);
    }

    [TestMethod]
    public void CreateInsertsShip()
    {
        Ship ship = new Ship { Name = "New Ship" };

        // Arrange
        var repository = Mock.Of<IShipRepository>();
        var controller = new ShipController(repository);

        // Act
        controller.Create(ship);

        // Assert
        Mock.Get(repository).Verify(m => m.Insert(ship));
    }

    [TestMethod]
    public void CreateRedirectsToRoot()
    {
        Ship ship = new Ship { Name = "New Ship" };

        // Arrange
        var repository = Mock.Of<IShipRepository>();
        var controller = new ShipController(repository);

        // Act
        RedirectResult result = controller.Create(ship);

        // Assert
        Assert.AreEqual("/", result.Url);
    }
}

This is using Moq to replace the repository and the arrange-act-assert pattern to perform the tests.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s