ASP.NET Web API 2 - 簡單Unit Testing

資源:http://www.asp.net/web-api/overview/testing-and-debugging/unit-testing-with-aspnet-web-api

本文講述的是爲Web API 2 app創建簡單的unit test。如何在solution中創建unit test,如何編寫用來檢查從controller方法中返回的值的test method(測試方法)。這裏展示的僅僅是簡單的數據場景,更多高級數據場景參考:ASP.NET Web API 2 - 模擬 EF(Entity Framework) 的Unit Testing。

創建Unit Test 項目

這裏有兩種方法:

  • 創建包含Unit Test的app

  • 在已存在的app中添加Unit Test

在solution上右鍵-> Add-> New Project-> Test-> Unit Test

創建Web API 2 app 

在Models下添加Products.cs後,build這個solution。

public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
在Controllers下添加ProductController

 public class ProductController : ApiController
    {
        List<Product> products = new List<Product>(); //Refer to as DataBase
        public ProductController() { }

        public ProductController(List<Product> products ) //The constructor enables Unit Test to pass test data
        {
            this.products = products;
        }

        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        public async Task<IEnumerable<Product>> GetAllProductAsync() //Async Used by Unit Test
        {
            return await Task.FromResult(GetAllProducts()); // Task.FromResult to minimize extraneous code
        }

        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }

        public async Task<IHttpActionResult> GetProductAsync(int id) //Async Used by Unit Test
        {
            return await Task.FromResult(GetProduct(id));
        }
    }

在Test中安裝NuGet 包

右鍵Test project-> Manage NuGet Package -> install "Microsoft ASP.NET Web API 2 Core"

創建Tests

默認Test project下面有一個UnitTest1.cs,可以更改這個文件也可刪除後重新添加。有一點需要注意的是,一定要是public class,不然運行不了。

本文中創建一個TestProductController.cs,該class中在[TestClass]標籤下面,所有的方法都在[TestMethod]下面,run unit test的時候會自動運行TestClass類下面的TestMethod方法。

[TestClass]
    public class TestProductController
    {
        [TestMethod]
        public void GetAllProducts_ShouldReturnAllProducts()
        {
            var testProducts = GetTestProducts();
            var controller = new ProductController(testProducts);
            var result = controller.GetAllProducts() as List<Product>;
            if (result != null)
            {
                Assert.AreEqual(testProducts.Count,result.Count);
            }
        }

        [TestMethod]
        public async Task GetAllProductsAsync_ShouldReturnAllProducts()
        {
            var testProducts = GetTestProducts();
            var controller = new ProductController(testProducts);

            var result = await controller.GetAllProductAsync() as List<Product>;
            Assert.IsNotNull(result);
            Assert.AreEqual((object) testProducts.Count, result.Count);

        }

        [TestMethod]
        public void GetProduct_ShouldReturnCorrectProduct()
        {
            var testProducts = GetTestProducts();
            var controller = new ProductController(testProducts);

            var result = controller.GetProduct(3) as OkNegotiatedContentResult<Product>;
            Assert.IsNotNull(result);
            Assert.AreEqual(testProducts[2].Name,result.Content.Name);
        }

        [TestMethod]
        public async Task GetProductAsync_ShouldReturnCorrectProduct()
        {
            var testProducts = GetTestProducts();
            var controller = new ProductController(testProducts);

            var result = await controller.GetProductAsync(3) as OkNegotiatedContentResult<Product>;
            Assert.IsNotNull(result);
            Assert.AreEqual(testProducts[2].Name, result.Content.Name);
        }

        [TestMethod]
        public void GetProduct_ShouldNotFindProduct()
        {
            var controller = new ProductController(GetTestProducts());

            var result = controller.GetProduct(999);
            Assert.IsInstanceOfType(result,typeof(NotFoundResult));
        }

        private List<Product> GetTestProducts()
        {
            var testProducts = new List<Product>
            {
                new Product() {Id = 1, Name = "Demo1", Price = 1},
                new Product() {Id = 2, Name = "Deom2", Price = 2.3M},
                new Product() {Id = 3, Name = "Deom2", Price = 4.3M},
                new Product() {Id = 4, Name = "Deom2", Price = 6.3M}
            };
            return testProducts;
        }
    }


運行測試

在一再Test-> Run -> 運行指定test,所有test,查看覆蓋率






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章