如何在集成测试中获取TempData

时间:2017-07-26 14:00:30

标签: c# asp.net-core asp.net-core-mvc integration-testing

我有一个控制器,其操作如下:

[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:

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

现在我正在编写集成测试(下面的代码摘要)来检查CancelOrder()方法是否按预期工作。在那里,我想访问TempData字典的值来检查它的正确性。

[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
    }
}

无论如何,我不知道如何从集成测试中访问它。有人知道该怎么做以及是否有办法呢?

1 个答案:

答案 0 :(得分:6)

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

[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");

}