我有一个MVC控制器类,我正在尝试进行单元测试。
特定的ActionResult就像这样
public ActionResult Create(Shipment newShipment)
{
do some stuff to create a shipmentID
...
return RedirectToAction("AddUnit",newShipment.ShipmentID);
}
我已经模拟了控制器上下文等,现在我想测试传递给RedirectToAction调用的newShipment.ShipmentID是我期望的。
我有一个测试(在设置阶段有大量的事情嘲笑)
[Test]
public void CreateSuccess()
{
//Arrange
var shipment = new Shipment();
shipment.Widgets = 2; //Make sure it a valid shipment otherwise
//Act
var result = controller.Create(shipment) as RedirectToRouteResult;
//Assert
Assert.IsNotNull(result);
Assert.AreEqual("AddUnits", result.RouteValues["action"]);
Assert.IsNull(result.RouteValues["controller"]);
...
现在我想找一个Assert来检查我传递给RedirectToAction的shipmentID是否正确。如何检索其值?
(我相信这段代码适用于实际(即实际视图获取正确的货件ID),但我想编写单元测试。)
答案 0 :(得分:3)
实际上,RedirectToActions可以采用参数;下面是我如何在一个中测试正确参数的简化示例。我正在使用NUnit& FluentAssertions在这里。
[HttpPost]
public ActionResult RedirectMethod()
{
return RedirectToAction("Index", "Home", new { parameter = "Value" });
}
然后测试:
[Test]
public void RedirectSetsExpectedParameters()
{
var result = controller.RedirectMethod();
var redirectResult = result.As<RedirectToRouteResult>();
var expectedRedirectValues = new RouteValueDictionary
{
{ "parameter", "Value" },
{ "action", "Index" },
{ "controller", "Home" }
};
redirectResult
.RouteValues
.ShouldBeEquivalentTo(expectedRedirectValues,
"The redirect should look as I expect, including the parameters");
}
答案 1 :(得分:1)
这里我给出了一个重定向到行动的样本
public ActionResult Signupsuccess(string account_code, string plan)
{
..........
do some stuff
return RedirectToAction("SubscriptionPlan", "Settings");
}
我已经模拟了controllercontext并将一些参数传递给从控制器到测试方法的RedirectToAction调用。最后它测试了预期和实际
[TestMethod的()]
public void SignupsuccessTest()
{
HomeController target = new HomeController(); // TODO: Initialize to an appropriate value
string account_code = "B898YB7"; // TODO: Initialize to an appropriate value
string plan = "Application-BASIC"; // TODO: Initialize to an appropriate value
var ControllerContext = new Mock<ControllerContext>();
var context = target.HttpContext;
ControllerContext.SetupGet(p => p.HttpContext.Session["MerchantID"]).Returns("15");
ControllerContext.SetupGet(p => p.HttpContext.Session["FriendlyIdentifier"]).Returns("3d649876-19f5-48d2-af03-ca89083ae712");
target.ControllerContext = controllerContext.Object;
var action = (RedirectToRouteResult)target.Signupsuccess(account_code, plan);
action.RouteValues["action"].Equals("SubscriptionPlan");
action.RouteValues["controller"].Equals("Settings");
Assert.AreEqual("SubscriptionPlan", action.RouteValues["action"]);
Assert.AreEqual("Settings", action.RouteValues["controller"]);
}
我希望它对你有所帮助。谢谢你