[UnitTest]針對Controller中的ViewResult進行驗證

今天我們來對.Net Mvc中的Controller中的ViewResult進行驗證

我使用的方法很簡單

MSTest + FluentAssertions (需從Nuget下載,但其實用VS內建的Assert也沒差)

 

一樣來看簡單明瞭的例子

Controller

using System.Web.Mvc;

namespace MySample.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Sample(int a, int b)
        {
            ViewBag.Result = Add(a, b);   //要測的東西

            return View();
        }

        private int Add(int a, int b)
        {
            return a + b;
        }
    }
}

 

Test case

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Mvc;
using FluentAssertions;

namespace MySample.Controllers.Tests
{
    [TestClass()]
    public class HomeControllerTests
    {
        HomeController controller = new HomeController();

        [TestMethod()]
        public void SampleTest()
        {
            //act
            ViewResult result = controller.Sample(a: 1, b: 2) as ViewResult;

            //assert
            (3).Should().Be(result.ViewBag.Result);
        }
    }
}