C# Mvc 5单元测试-设置控制器的viewbag值
我有一个索引页,可以有上次搜索的C# Mvc 5单元测试-设置控制器的viewbag值,c#,asp.net-mvc,unit-testing,asp.net-mvc-5,viewbag,C#,Asp.net Mvc,Unit Testing,Asp.net Mvc 5,Viewbag,我有一个索引页,可以有上次搜索的ViewBag值。我想设置控制器,以便在调用我的测试系统之前能够设置此ViewBag值(ProductManagementController) 索引操作 [HttpPost] public async Task<ActionResult> Index(ProductManagementVm postedVm) { // Reset pagination if new search if (postedVm.BookSearch !=
ViewBag
值。我想设置控制器,以便在调用我的测试系统之前能够设置此ViewBag
值(ProductManagementController
)
索引操作
[HttpPost]
public async Task<ActionResult> Index(ProductManagementVm postedVm)
{
// Reset pagination if new search
if (postedVm.BookSearch != ViewBag.lastSearch)
{
postedVm.Page = 1;
}
var httpResponseMessage = await_httpService.GetAsync(_urlConfigurations.GetProductList);
var vm = _productFactory.BuildProductManagementVm(
await Task.Run(() => httpResponseMessage.Content.ReadAsStringAsync()), postedVm);
vm.BookSearch = postedVm.BookSearch;
if (string.IsNullOrEmpty(postedVm.BookSearch))
{
postedVm.BookSearch = string.Empty;
}
ViewBag.lastSearch = postedVm.BookSearch;
return View(vm);
}
从ViewData
属性获取其数据
public dynamic ViewBag
{
get
{
if (_dynamicViewDataDictionary == null)
{
_dynamicViewDataDictionary = new DynamicViewDataDictionary(() => ViewData);
}
return _dynamicViewDataDictionary;
}
}
因此,您需要在ViewBag中填充您想要访问的值
这是一个POC
[TestClass]
public class ViewBagTests {
[TestMethod]
public void ViewBag_ShouldBe_PrePopulated() {
//Arrange
var SUT = new TargetController();
var expected = "Hey I'm the old search string :D";
SUT.ViewData["LastSearch"] = expected;
//Act
var actual = SUT.Index() as ViewResult;
//Assert
Assert.AreEqual(expected, actual.Model);
}
class TargetController : Controller {
public ActionResult Index() {
var previous = ViewBag.LastSearch;
return View((object)previous);
}
}
}
这个问题解决了吗?
public dynamic ViewBag
{
get
{
if (_dynamicViewDataDictionary == null)
{
_dynamicViewDataDictionary = new DynamicViewDataDictionary(() => ViewData);
}
return _dynamicViewDataDictionary;
}
}
[TestClass]
public class ViewBagTests {
[TestMethod]
public void ViewBag_ShouldBe_PrePopulated() {
//Arrange
var SUT = new TargetController();
var expected = "Hey I'm the old search string :D";
SUT.ViewData["LastSearch"] = expected;
//Act
var actual = SUT.Index() as ViewResult;
//Assert
Assert.AreEqual(expected, actual.Model);
}
class TargetController : Controller {
public ActionResult Index() {
var previous = ViewBag.LastSearch;
return View((object)previous);
}
}
}