如何模拟属于另一个方法内部的方法?

发布于 2025-01-09 03:14:44 字数 910 浏览 1 评论 0原文

这是我的示例代码:

public class PersonRepository : IPersonRepository
{
    private readonly IOrderRepository _orderRepository;
    public PersonRepository(IOrderRepository orderRepo)
    {
    _orderRepository = orderRepo;
    }
    public List<Person> GetPersonsList()
    {
    // some codes here
    //....
    
    // this function need to mock? because due to database connection no data coming in this orders variable,
    // so that the lines is not covered by code coverage
    List<Order> orders = _orderRepository.GetOrders(); //here doing some operation based on database
    foreach(Order order in orders)
    {
       // some code here
       //..
    }
    } 
}

// xunit

[Fact]
public void PersonRepository_GetPersonsList()
{
   _personRepository.GetPersonList();
}

如何模拟 _orderRepository.GetOrders();函数以便它附带一些示例数据并执行整个代码?

Here is my sample code:

public class PersonRepository : IPersonRepository
{
    private readonly IOrderRepository _orderRepository;
    public PersonRepository(IOrderRepository orderRepo)
    {
    _orderRepository = orderRepo;
    }
    public List<Person> GetPersonsList()
    {
    // some codes here
    //....
    
    // this function need to mock? because due to database connection no data coming in this orders variable,
    // so that the lines is not covered by code coverage
    List<Order> orders = _orderRepository.GetOrders(); //here doing some operation based on database
    foreach(Order order in orders)
    {
       // some code here
       //..
    }
    } 
}

// xunit

[Fact]
public void PersonRepository_GetPersonsList()
{
   _personRepository.GetPersonList();
}

how to mock the _orderRepository.GetOrders(); function so that it will come with some sample data and execute the entire code?

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

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

发布评论

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

评论(1

め七分饶幸 2025-01-16 03:14:44

您需要创建 IOrderRepository 的模拟并设置 GetOrders 方法以返回所需的数据。
以下是使用 Moq 的示例:

[Fact]
public void PersonRepository_GetPersonsList()
{
   var orderRepositoryMock = new Mock<IOrderRepository>();
   orderRepository.Setup(o => o.GetOrders()).Returns(new List<Order>()); // Setup the data you want to return here

   var personRepository = new PersonRepository(orderRepository.Object);

   // Do the rest of your test
}

You need to create a mock of your IOrderRepository and setup the GetOrders method to return the data you want.
Here is an example using Moq:

[Fact]
public void PersonRepository_GetPersonsList()
{
   var orderRepositoryMock = new Mock<IOrderRepository>();
   orderRepository.Setup(o => o.GetOrders()).Returns(new List<Order>()); // Setup the data you want to return here

   var personRepository = new PersonRepository(orderRepository.Object);

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