【问题标题】:Error message while working with mocking in unit test在单元测试中使用模拟时出现错误消息
【发布时间】:2015-10-19 21:38:51
【问题描述】:

抱歉标题不好。

我正在尝试做一些单元测试。我有以下控制器:

public class ProductController : Controller
{
    private IProductRepository repository;
    public int PageSize = 4;
    //Declar the dependency on IProductRepository
    public ProductController(IProductRepository productRepository)
    {
        this.repository = productRepository;
    }
    // GET: Product

    public ViewResult List(int page = 1)
    {
    return View(repository.Products.OrderBy(p => p.ProductID).Skip((page-1) * PageSize).Take(PageSize));
    }
}

我要对页面分页进行单元测试。

这是我的单元测试:

[TestMethod]
public void Can_Paginate()
{
    //Arrange
    Mock<IProductRepository> mock = new Mock<IProductRepository>();
    mock.Setup(m => m.Products).Returns(new Product[]
    {
        new Product {ProductID = 1, Name = "P1" },
        new Product {ProductID = 2, Name = "P2" },
        new Product {ProductID = 3, Name = "P3" },
        new Product {ProductID = 4, Name = "P4" },
        new Product {ProductID = 5, Name = "P5" }
    });

    ProductController controller = new ProductController(mock.Object);
            controller.PageSize = 3;

    //Act
    IEnumerable<Product> result = (IEnumerable<Product>)controller.List(2).Model;

    //Assert
    Product[] prodArray = result.ToArray();
    Assert.IsTrue(prodArray.Length == 2);
    Assert.AreEqual(prodArray[0].Name, "P4");
    Assert.AreEqual(prodArray[1].Name, "P5");
}

我在测试文件中收到以下错误消息:

这是什么意思?

【问题讨论】:

  • 您的项目 dll 使用比您在测试项目中引用的 dll 更新的 dll。只需从您的测试项目中删除 dll,然后添加正确的。
  • @OldFox:如何删除 dll?
  • 我将其发布为答案...

标签: c# unit-testing mocking


【解决方案1】:

您的项目 dll 使用比您在测试项目中引用的 dll 更新的 dll。只需从您的测试项目中删除 dll,然后添加正确的:

在解决方案资源管理器中选择测试项目 -> 参考 -> 右键单击​​ System.Web.Mvc -> 删除 (How to: Add or Remove References)

添加正确版本的 System.Web.Mvc 是 5.2.3.0

编辑

ASP.NET MVC 有一个nuget package。这是添加程序集的正确方法

【讨论】:

  • 我应该在 Assemblies 选项卡中选择 Framework och Extension 吗?
  • @Bryan 我不知道确切的位置,但是如果您单击程序集,那么您会在右侧面板上看到版本。
  • 是的,但是如何添加新版本的 dll?
  • @Bryan 您正在寻找的 Dll 有一个 nuget 包。右键单击 References -> Manage nuget packages -> 在搜索框中键入 mvc 然后添加包。(我编辑了我的答案)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-22
  • 1970-01-01
  • 2021-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多