如何模拟属于另一个方法内部的方法?
这是我的示例代码:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要创建 IOrderRepository 的模拟并设置 GetOrders 方法以返回所需的数据。
以下是使用 Moq 的示例:
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: