Mocking a TempData in ASP.NET Core in MSTest

2019-03-01 09:23发布

问题:

public ActionResult View(string name)
{
    if (TempData["SessionVariable"] != null)
    {
        FileName = name;  
        return View();
    }
    else
    {  
        return RedirectToAction("index", "Home");
    }

}

TestMethod

public void UseCaseView_CorrectRequirements()
{
    var mock = new Mock<Controller>();
    mock.Setup(p => p.TempData["SessionVariable"]).Returns("admin");
    Controller.View("SAMPLE.xml");           
}

It throws an error such as ,

Result StackTrace:

at Moq.Mock.ThrowIfSetupExpressionInvolvesUnsupportedMember(Expression setup, MethodInfo method) in C:\projects\moq4\Source\Mock.cs:line 883 at Moq.Mock.SetupGetPexProtected[T,TProperty](Mock1 mock, Expression1 expression, Condition condition) in C:\projects\moq4\Source\Mock.cs:line 537 at Moq.Mock.SetupGet[T,TProperty](Mock1 mock, Expression1 expression, Condition condition) in C:\projects\moq4\Source\Mock.cs:line 517 at Moq.Mock.SetupPexProtected[T,TResult](Mock1 mock, Expression1 expression, Condition condition) in C:\projects\moq4\Source\Mock.cs:line 507 at Moq.Mock.Setup[T,TResult](Mock1 mock, Expression1 expression, Condition condition) in C:\projects\moq4\Source\Mock.cs:line 484 at Moq.QueryableMockExtensions.FluentMock[T,TResult](Mock1 mock, Expression1 setup) in C:\projects\moq4\Source\Linq\Mocks.cs:line 224 at lambda_method(Closure ) at Moq.Mock.GetTargetMock(Expression fluentExpression, Mock mock) in C:\projects\moq4\Source\Mock.cs:line 856 at Moq.Mock.SetupPexProtected[T,TResult](Mock1 mock, Expression1 expression, Condition condition) in C:\projects\moq4\Source\Mock.cs:line 505 at Moq.Mock.Setup[T,TResult](Mock1 mock, Expression1 expression, Condition condition) in C:\projects\moq4\Source\Mock.cs:line 484 at SE_WEBAPP.Tests.TestControllers.UsecaseControllerTests.UseCaseView_CorrectRequirements() in

D:\Public\SE_WEBAPP_TESTCASE\SE_WEBAPP\SE_WEBAPP.Tests\TestControllers\UsecaseControllerTests.cs:line 23

Result Message: Test method SE_WEBAPP.Tests.TestControllers.UsecaseControllerTests.UseCaseView_CorrectRequirements threw exception: System.NotSupportedException: Invalid setup on a non-virtual (overridable in VB) member: mock => mock.TempData

回答1:

In asp.net-core, Controller.TempData is a public property, so you can easily access it and set the desired key/value

public void UseCaseView_CorrectRequirements() {
    // Arrange
    var httpContext = new DefaultHttpContext();
    var tempData = new TempDataDictionary(httpContext, Mock.Of<ITempDataProvider>());
    tempData["SessionVariable"] = "admin";        
    var controller = new UsecaseController() {
        TempData = tempData
    };
    var expected = "SAMPLE.xml";

    //Act
    var view = controller.View(expected) as ViewResult;
    var actual = controller.FileName;

    //Assert
    Assert.AreEqual(expected, actual);
}