ProductsControllerTests

C#

Public Domain

Unit tests on the products controller using Moq to create fake data.

Download (right click, save as, rename as appropriate)

Embed

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using DomainModel.Abstract;
using DomainModel.Entities;
using Moq;
using WebUI.Controllers;

namespace Tests
{
    [TestFixture]
    public class ProductsControllerTests
    {
        [Test]
        public void List_Presents_Correct_Page_Of_Products()
        {
            // Arrange: 5 products in the repo
            IProductsRepository repository = MockProductsRepository(
                new Product { Name = "P1" }, new Product { Name = "P2" },
                new Product { Name = "P3" }, new Product { Name = "P4" },
                new Product { Name = "P5" }
                );
            ProductsController controller = new ProductsController(repository);
            controller.PageSize = 3;

            // Act: Request the second page (page size = 3)
            var result = controller.List(2);

            // Assert: Check the results
            Assert.IsNotNull(result, "didn't render view");
            var products = result.ViewData.Model as IList<Product>;
            Assert.AreEqual(2, products.Count, "Got wrong # of products");
            Assert.AreEqual(2, (int)result.ViewData["CurrentPage"], "Wrong Page Number");
            Assert.AreEqual(2, (int)result.ViewData["TotalPages"], "Wrong page count");
            // Make Sure the correct objects were selected
            Assert.AreEqual("P4", products[0].Name);
            Assert.AreEqual("P5", products[1].Name);
        }

        static IProductsRepository MockProductsRepository(params Product[] prods)
        {
            // Generate an implementor of IProductsRepository at runtime using Moq
            var mockProductsRepos = new Mock<IProductsRepository>();
            mockProductsRepos.Setup(X => X.Products).Returns(prods.AsQueryable());
            return mockProductsRepos.Object;
        }
    }
}