using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Results;
using UnitTestMocking.Controllers;
using UnitTestMocking.Models;
namespace UnitTestMocking.Tests
{
[TestClass]
public class TestItemController
{
[TestMethod]
public void PostItem_ShouldReturnSameItem()
{
var controller = new ItemController(new TestUnitTestMockingConext());
var item = GetDemoItem();
var result =
controller.PostItem(item) as CreatedAtRouteNegotiatedContentResult<Item>;
Assert.IsNotNull(result);
Assert.AreEqual(result.RouteName, "DefaultApi");
Assert.AreEqual(result.RouteValues["id"], result.Content.ID);
Assert.AreEqual(result.Content.ItemName, item.ItemName);
}
[TestMethod]
public void PutItem_ShouldReturnStatusCode()
{
var controller = new ItemController(new TestUnitTestMockingConext());
var item = GetDemoItem();
var result = controller.PutItem(item.ID, item) as StatusCodeResult;
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(StatusCodeResult));
Assert.AreEqual(HttpStatusCode.NoContent, result.StatusCode);
}
[TestMethod]
public void PutItem_ShouldFail_WhenDifferentID()
{
var controller = new ItemController(new TestUnitTestMockingConext());
var badresult = controller.PutItem(999, GetDemoItem());
Assert.IsInstanceOfType(badresult, typeof(BadRequestResult));
}
[TestMethod]
public void GetItem_ShouldReturnItemWithSameID()
{
var context = new TestUnitTestMockingConext();
context.Items.Add(GetDemoItem());
var controller = new ItemController(context);
var result = controller.GetItem(3) as OkNegotiatedContentResult<Item>;
Assert.IsNotNull(result);
Assert.AreEqual(3, result.Content.ID);
}
[TestMethod]
public void GetItems_ShouldReturnAllItems() {
var context = new TestUnitTestMockingConext();
context.Items.Add(new Item{ ID = 1, ItemName = "Demo1", Cost = 20 });
context.Items.Add(new Item { ID = 2, ItemName = "Demo2", Cost = 30 });
context.Items.Add(new Item { ID = 3, ItemName = "Demo3", Cost = 40 });
var controller = new ItemController(context);
var result = controller.GetItems() as TestItemDbSet;
Assert.IsNotNull(result);
Assert.AreEqual(3, result.Local.Count);
}
[TestMethod]
public void DeleteItem_ShouldReturnOK() {
var context = new TestUnitTestMockingConext();
var item = GetDemoItem();
context.Items.Add(item);
var controller = new ItemController(context);
var result = controller.DeleteItem(3) as OkNegotiatedContentResult<Item>;
Assert.IsNotNull(result);
Assert.AreEqual(item.ID, result.Content.ID);
}
Item GetDemoItem()
{
return new Item() { ID = 3, ItemName = "Demo name", Cost = 5 };
}
}
}