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");
}
它会引发错误,例如,
结果StackTrace:
在Moq.Mock.ThrowIfSetupExpressionInvolvesUnsupportedMember(Expression 设置,MethodInfo方法)在C:\ projects \ moq4 \ Source \ Mock.cs:line 883中 在Moq.Mock.SetupGetPexProtected [T,TProperty](Mock1 mock, Expression
1表达式,条件条件)中 C:\ projects \ moq4 \ Source \ Mock.cs:线537在 Moq.Mock.SetupGet [T,TProperty](模拟1 mock, Expression
1个表达式, 条件条件)在C:\ projects \ moq4 \ Source \ Mock.cs:第517行 Moq.Mock.SetupPexProtected [T,TResult](模拟1 mock, Expression
1 表达式,条件条件) C:\ projects \ moq4 \ Source \ Mock.cs:第507行位于 Moq.Mock.Setup [T,TResult](模拟1 mock, Expression
1个表达式, 条件条件)在C:\ projects \ moq4 \ Source \ Mock.cs:线484在 Moq.QueryableMockExtensions.FluentMock [T,TResult](模拟1 mock, Expression
1设置)在C:\ projects \ moq4 \ Source \ Linq \ Mocks.cs:line 224 在Moq.Mock.GetTargetMock(Expression)的lambda_method(Closure) C:\ projects \ moq4 \ Source \ Mock.cs:line中的fluentExpression,Mock模拟) 856,位于Moq.Mock.SetupPexProtected [T,TResult](Mock1 mock, Expression
1表达式,条件条件)中 C:\ projects \ moq4 \ Source \ Mock.cs:505行位于 Moq.Mock.Setup [T,TResult](模拟1 mock, Expression
1个表达式, 条件条件)在C:\ projects \ moq4 \ Source \ Mock.cs:线484在 SE_WEBAPP.Tests.TestControllers.UsecaseControllerTests.UseCaseView_CorrectRequirements() 在D:\ Public \ SE_WEBAPP_TESTCASE \ SE_WEBAPP \ SE_WEBAPP.Tests \ TestControllers \ UsecaseControllerTests.cs:第23行
结果消息:测试方法 SE_WEBAPP.Tests.TestControllers.UsecaseControllerTests.UseCaseView_CorrectRequirements 引发异常:System.NotSupportedException:无效的设置 非虚拟成员(在VB中可重写):mock =>模拟.TempData
答案 0 :(得分:3)
在asp.net-core中,Controller.TempData
是公共财产,因此您可以轻松访问它并设置所需的键/值
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);
}