【问题标题】:How to test that action uses argument?如何测试该动作使用参数?
【发布时间】:2014-08-23 09:48:56
【问题描述】:

我应该使用测试驱动开发,但在这种特殊情况下,由于我遇到了麻烦,我首先实现了 action 方法。它看起来像这样:

public ViewResult Index(int pageNumber = 1)
{
    var posts = repository.All();
    var model = new PagedList<Post>(posts, pageNumber, PageSize);

    return View(model);
}

存储库和PagedList&lt;&gt; 都已经过测试。现在我想验证,当动作被赋予页码时,页码实际上是被考虑的。

private Mock<IPostsRepository> repository;
private HomeController controller;

[Test]
public void Index_Doohickey()
{
    var actual = controller.Index(2);

    // .. How do I test that the controller actually uses the page number here?
}

【问题讨论】:

    标签: c# asp.net-mvc unit-testing tdd


    【解决方案1】:

    我猜你正在使用这个pagedlist nuget? https://github.com/troygoode/PagedList/ 该组件有一个方法来获取一些元数据,然后有一个当前页码的属性。

    https://github.com/troygoode/PagedList/blob/master/src/PagedList/PagedListMetaData.cs

    您在测试中可能需要做的是检查视图中的模型(您的实际变量)。 将actual 转换为ViewResult 以获取您的模型。

    例如

    ViewResult actual = controller.Index(2) as ViewResult;
    
    // not 100% sure about the code below, I didn't tried it out
    var list = actual.Model as PagedList<Post>;
    var pgNumber = list.GetMetaData().PageNumber // <- assert this
    

    您可能还必须模拟存储库以返回一个或多个元素。如果列表为空,不知道这个视图列表的行为如何......

    【讨论】:

    • 我实际上并没有使用那个库。不过,我理解您的回答,并会根据该库的工作方式来查看是否可以使某些工作正常进行。谢谢。
    猜你喜欢
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    相关资源
    最近更新 更多