如何在ASP MVC CORE中测试使用TempData的控制器方法

时间:2019-04-30 05:34:14

标签: c# asp.net-mvc asp.net-core mstest

我想为控制器方法编写测试,但是我在方法中使用的NullpointexceprionTempData["EditMember"] = false;

我已经阅读了几个类似的主题,但是还没有找到解决该问题的方法。我尝试使用模拟,但由于所有示例都不希望编译,因此我也失败了。

这是我的控制器方法


    public class MemberController : Controller
    {
        private readonly UnitOfWork _unitOfWork;

        public MemberController(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork as UnitOfWork;
        }


        public IActionResult CreateUpdate(string id = null, string table = null)
        {

            MemberViewModel model = null;

            TempData["EditMember"] = false;
            if (id != null)
            {
                TempData["EditMember"] = true;
                var member = _unitOfWork.MemberRepositories.FindBySRU(id);
                model = AutoMapper.Mapper.Map<Member, MemberViewModel>(member);
            }


            if (model == null)
                model = new MemberViewModel();

            TempData["HealthIssues"] = JsonConvert.SerializeObject(model.Player);
            TempData["Guardians"] = JsonConvert.SerializeObject(model.Player.Junior);

            return View(model);
        }

测试方法

        [TestMethod]
        public void test()
        {
            //Arrange

            var memberController = new MemberController(new UnitOfWork(new DatabaseModel()));


            //Act
            var viewResult = memberController.CreateUpdate() as ViewResult;

            //Assert
        }

是否有一种简单的方法可以使用TempData在ASP CORE中启动这样的测试?

1 个答案:

答案 0 :(得分:1)

您必须先创建一个ITempDataDictionary对象,然后在访问它之前将其分配给控制器上的TempData属性。您可以使用模拟轻松地做到这一点。这是Moq的(简化)示例:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using TestProjectMvc.Controllers;

namespace TestProjectMvc.Tests
{
    [TestClass]
    public class MemberControllerTests
    {
        [TestMethod]
        public void CreateUpdateTest()
        {
            ITempDataProvider tempDataProvider = Mock.Of<ITempDataProvider>();
            TempDataDictionaryFactory tempDataDictionaryFactory = new TempDataDictionaryFactory(tempDataProvider);
            ITempDataDictionary tempData = tempDataDictionaryFactory.GetTempData(new DefaultHttpContext());

            MemberController controller = new MemberController(new UnitOfWork())
            {
                TempData = tempData
            };

            ViewResult viewResult = controller.CreateUpdate(null) as ViewResult;

            Assert.IsFalse((bool)viewResult.TempData["EditMember"]);

            viewResult = controller.CreateUpdate("123") as ViewResult;

            Assert.IsTrue((bool)viewResult.TempData["EditMember"]);
        }
    }
}