带最小起订量的单元测试存储库

发布于 2024-10-05 12:57:03 字数 1027 浏览 1 评论 0原文

我对 Moq 完全陌生,到目前为止刚刚遵循 Pro asp.net 框架中概述的示例。在本书中,一些琐碎的事情被放置在控制器中,例如通过 id 获取客户 - 可能是出于简洁的原因。我决定将这种类型的功能放在存储库中,然后在控制器中调用它,如下所示“customerRepository.GetCustomerByID(id);”测试此类内容的最佳方法是什么?我创建了以下单元测试,由于某种原因,该测试返回空客户。

List<Customer> customer = new List<Customer>();

customer.Add(new Customer { CustomerId = 1, FirstName = "test", LastName = "wods", Sex = true });
mockRepos = new Moq.Mock<ICustomerRepository>();
mockRepos.Setup(x => x.Customers).Returns(customer.AsQueryable());

CustomersController controller = new CustomersController(mockRepos.Object);

//Act
ViewResult results = controller.Edit(1);

var custRendered = (Customer)results.ViewData.Model;
Assert.AreEqual(2, custRendered.CustomerId);
Assert.AreEqual("test", custRendered.FirstName);

我想我的控制器

public ViewResult Edit(int id)
{
    Customer customer = customerRepository.GetCustomerByID(id);           

    return View(customer); //this just returns null??
}

很愚蠢,但任何帮助将不胜感激。

I'm utterly new to Moq and so far have just follwed the examples outlined in Pro asp.net framework. In the book, some of the crud is placed in the controller, such as getting customer by id - possibly for reasons of brevity. I've decided to place that type of functionality in the repository and just call it in the controller like so "customerRepository.GetCustomerByID(id);" What's the best way to test something like this?I've created the following unit test, which for some reason returns a null Customer.

List<Customer> customer = new List<Customer>();

customer.Add(new Customer { CustomerId = 1, FirstName = "test", LastName = "wods", Sex = true });
mockRepos = new Moq.Mock<ICustomerRepository>();
mockRepos.Setup(x => x.Customers).Returns(customer.AsQueryable());

CustomersController controller = new CustomersController(mockRepos.Object);

//Act
ViewResult results = controller.Edit(1);

var custRendered = (Customer)results.ViewData.Model;
Assert.AreEqual(2, custRendered.CustomerId);
Assert.AreEqual("test", custRendered.FirstName);

And the controller

public ViewResult Edit(int id)
{
    Customer customer = customerRepository.GetCustomerByID(id);           

    return View(customer); //this just returns null??
}

I imagine I'm being very silly, but any help would be uber appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

又爬满兰若 2024-10-12 12:57:03

您需要将模拟设置为期望调用 GetCustomerById 而不是 Customers 属性。像这样的东西:

mockRepos.Setup(x => x.GetCustomerById(1)).Returns(customer[0]);

you need to set your mock up to expect a call to GetCustomerById rather than the Customers property. Something like this:

mockRepos.Setup(x => x.GetCustomerById(1)).Returns(customer[0]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文