Moq:如何根据方法参数返回结果?

发布于 2024-12-12 08:03:16 字数 817 浏览 0 评论 0原文

ICustomerRepository 定义:Customer GetCustomerByID(int CustomerID);

//Arrange
var customers = new Customer()
{
   new Customer() { CustomerID = 1, Name = "Richard" },
   new Customer() { CustomerID = 2, Name = "Evan" },
   new Customer() { CustomerID = 3, Name = "Marie-France" },
}.AsQueryable(); 

Mock<ICustomerRepository> mock = new Mock<ICustomerRepository>();

我如何告诉 Moq 根据 CustomerID 参数返回正确的客户???

我已经能够设置第一部分,但不能设置返回对象。

 mock.Setup(m => m.GetCustomerByID(It.Is<int>(i => i >= 0))).Returns(/// To be define///)

想法是得到与此相同的结果:

public Customer GetCustomerByID(int CustomerID)
{
  return customers.FirstOrDefault(c => c.CustomerID == CustomerID);
}

感谢您的帮助

ICustomerRepository define: Customer GetCustomerByID(int CustomerID);

//Arrange
var customers = new Customer()
{
   new Customer() { CustomerID = 1, Name = "Richard" },
   new Customer() { CustomerID = 2, Name = "Evan" },
   new Customer() { CustomerID = 3, Name = "Marie-France" },
}.AsQueryable(); 

Mock<ICustomerRepository> mock = new Mock<ICustomerRepository>();

How do I tell Moq to return the correct customer depending on the CustomerID paremeter???

I've been able to set up the first part, but not the return object.

 mock.Setup(m => m.GetCustomerByID(It.Is<int>(i => i >= 0))).Returns(/// To be define///)

The Idea is to have the same result as this:

public Customer GetCustomerByID(int CustomerID)
{
  return customers.FirstOrDefault(c => c.CustomerID == CustomerID);
}

Thanks for helping

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

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

发布评论

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

评论(1

烟─花易冷 2024-12-19 08:03:16
mock.Setup(x => x.GetCustomerByID(It.IsAny<int>()))
    .Returns((int id) => 
    customers.FirstOrDefault(c => c.CustomerID == id));

只需将客户设置为 List - 无需 AsQueryable。

mock.Setup(x => x.GetCustomerByID(It.IsAny<int>()))
    .Returns((int id) => 
    customers.FirstOrDefault(c => c.CustomerID == id));

Just make customers a List<Customer> - no need for AsQueryable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文