如何在集成测试中获取TempData [英] How to get TempData in an integration test

查看:91
本文介绍了如何在集成测试中获取TempData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个执行以下操作的控制器:

I have a controller with the following actions:

[HttpGet]
public IActionResult Index()
{
    return View();
}

[HttpPost]
[Route(
    "/MyShop/OrderDetails/CancelOrder", 
    Name = UrlRouteDefinitions.MyShopOrderDetailsCancelOrder)]
[ValidateAntiForgeryToken]
public IActionResult CancelOrder(MyViewModel viewModel)
{
    var isCancelSuccessful = _orderBusinessLogic.CancelOrderById(viewModel.Order.Id);

    if (isCancelSuccessful)
    {
        //to show a success-message after the redirect
        this.TempData["SuccessCancelOrder"] = true;
    }

    return RedirectToRoute(UrlRouteDefinitions.MyShopOrderDetailsIndex, new
    {
        orderId = viewModel.Order.Id
    });
}

然后,在上面提到的Controller的视图中,我还有以下HTML片段:

Then I also have the following piece of HTML in the View for the Controller mentioned above:

<div class="panel-body">
    @if (TempData["SuccessCancelOrder"] != null) 
    {
        //show the message
        @TempData["SuccessCancelOrder"].ToString();
    }
</div>

现在,我正在编写一个集成测试(下面的代码摘要),以检查CancelOrder()方法是否按预期工作.在这里,我想访问TempData词典的值以检查其正确性.

Now I'm writing an integration test (code-summary below) to check if the CancelOrder() method works as expected. There I'd like to access the value of the TempData dictionary to check its correctness.

[TestMethod]
public void MyTest()
{
    try
    {
        //Arrange: create an Order with some Products
        var orderId = CreateFakeOrder();

        //Open the Order Details page for the arranged Order
        var httpRequestMessage = base.PrepareRequest(
            HttpMethod.Get,
            "/MyShop/OrderDetails?orderId=" + orderId,
            MediaTypeEnum.Html);

        var httpResponse    = base.Proxy.SendAsync(httpRequestMessage).Result;
        var responseContent = httpResponse.Content.ReadAsStringAsync().Result;
        var viewModel       = base.GetModel<MyViewModel>(responseContent);

        Assert.AreEqual(HttpStatusCode.OK, httpResponse.StatusCode);


        //Try to execute a POST to cancel the Order
        httpRequestMessage = base.PrepareRequest(
            HttpMethod.Post,
            "/MyShop/OrderDetails/CancelOrder",
            MediaTypeEnum.Html,
            httpResponse, content: viewModel);


        httpResponse = base.Proxy.SendAsync(httpRequestMessage).Result;
        var expectedRedirectLocation = $"{this.RelativeHomeUrl}/MyShop/OrderDetails?orderId=" + orderId;
        var receivedRedirectLocation = WebUtility.UrlDecode(httpResponse.Headers.Location.ToString());


        //we expect that the Order Details page will be reloaded 
        //with the ID of the already cancelled Order
        Assert.AreEqual(HttpStatusCode.Redirect, httpResponse.StatusCode);

        //-----------------------------------------------------------
        //here I'm going to re-execute a GET-request 
        //on the Order Details page. 
        //
        //Then I need to check the content of the message 
        //that's been written in the TempData
        //-----------------------------------------------------------
    }
    finally
    {
        //delete the arranged data
    }
}

无论如何,我不知道如何从集成测试中访问它.有人知道怎么做吗,如果有办法的话?

In any case, I don't know how to access it from my integration test. Does anybody know how to do it and if there's a way at all?

推荐答案

Controller.TempData是公开的,因此您可以轻松地访问它并检查键/值是否存在

Controller.TempData is public so you can easily access it and check if your key/value exists

[TestMethod]
public void TempData_Should_Contain_Message() {    
    // Arrange
    var httpContext = new DefaultHttpContext();
    var tempData = new TempDataDictionary(httpContext, Mock.Of<ITempDataProvider>());
    var controller = new TestController();
    controller.TempData = tempData;

    // Act
    var result = controller.DoSomething();

    //Assert
    controller.TempData["Message"]
        .Should().NotBeNull()
        .And.BeEquivalentTo("Hello World");

}

这篇关于如何在集成测试中获取TempData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆