using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web.Http;
using System.Web.Http.Results;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WebServiceTest.Controllers;
using WebServiceTest.Models;
namespace WebServiceTest.Tests.Controllers {
[TestClass()]
public class ProductsControllerTest {
public CancellationToken _cancellationToken { get; set; }
public ProductsControllerTest() {
_cancellationToken = new CancellationToken();
}
// 取得所有產品項目明細
[TestMethod()]
public void GetAllProducts() {
ProductsController controller = new ProductsController();
IEnumerable<Product> result = controller.GetAllProducts();
Assert.IsNotNull(result); // 檢查有沒有資料
Assert.AreEqual(3, result.Count()); // 檢查資料的筆數
Assert.AreEqual("Tomato Soup", result.ElementAt(0).Name); // 資料內容比對
Assert.AreEqual("Yo-yo", result.ElementAt(1).Name); // 資料內容比對
Assert.AreEqual("Hammer", result.ElementAt(2).Name); // 資料內容比對
}
// 取得各產品的資料內容
[TestMethod()]
public void GetProduct() {
ProductsController controller = new ProductsController();
// 取得傳回的 IHttpActionResult, 轉成資料物件, 以取得內容
IHttpActionResult actionResult1 = controller.GetProduct(1);
var contentResult1 = (OkNegotiatedContentResult<Product>)actionResult1;
IHttpActionResult actionResult2 = controller.GetProduct(2);
var contentResult2 = (OkNegotiatedContentResult<Product>)actionResult2;
IHttpActionResult actionResult3 = controller.GetProduct(3);
var contentResult3 = (OkNegotiatedContentResult<Product>)actionResult3;
Assert.AreEqual("Tomato Soup", contentResult1.Content.Name); // 資料內容比對
Assert.AreEqual("Yo-yo", contentResult2.Content.Name); // 資料內容比對
Assert.AreEqual("Hammer", contentResult3.Content.Name); // 資料內容比對
}
}
}