单元测试控制器动作,重定向到另一个动作

时间:2017-01-27 10:40:29

标签: asp.net-mvc tdd

我正在按照TDD方法开发我的MVC网站。我有一个PaymentController,它将有一个动作方法MakePayment,我正在使用下面给出的测试方法进行测试:

[TestMethod]
public void MakePaymentLoad()
{
    PaymentController payController = new PaymentController();
    ViewResult payResult = payController.MakePayment() as ViewResult;
    Assert.IsNotNull(payResult);
}

[TestMethod]
public void MakePaymentResult()
{
    PaymentController payController = new PaymentController();
    Payment payment = new Payment {
        BillerId = 1,
        PayAmt = 1.0,                
        PayDt = DateTime.Now,
        ConfCode = null,
        BillAccount = "123",
        PayStatus = 1,
        FeeStatus = 1,
        Platform =1
    };
    ViewResult payResult = payController.MakePayment(payment) as ViewResult;
    PaymentResult result = payResult.Model as PaymentResult;
    Assert.IsNotNull(result.ConfCode);            
}

在上面给出的测试方法中,MakePaymentLoad仅检查是否呈现视图,MakePaymentResult检查视图模型中是否存在确认代码。

我的行动方法如下:

[HttpPost]
public ActionResult MakePayment(Payment payment)
{
    PaymentResult payResult = new PaymentResult {
        ConfCode = "123"
    };
    if (true)
    {
        TempData["ConfCode"] = "123";
        return RedirectToAction("Confirmation");
    }
    return View(payment);
}

public ViewResult MakePayment()
{            
    return View();
}

public ActionResult Confirmation()
{
    PaymentResult result = new PaymentResult {
        ConfCode = Convert.ToString(TempData["ConfCode"])
    };
    return View(result);
}

MakePaymentLoad传递,因为它仅检查是否呈现视图,而MakePaymentResult因操作方法的结果为空而失败,因为在RedirectToAcion内使用MakePayment's发布版本。请让我知道如何解决这个问题。

1 个答案:

答案 0 :(得分:2)

你应该像下面那样进行测试

var payResult = (RedirectToActionResult)payController.MakePayment(payment)

Assert.AreEqual("Confirmation", action.RouteValues["action"]);

当您返回重定向结果时,您不能指望模型作为回报。