SP Tutorials
SP Tutorials

Reputation: 25

How to mock a method which belong inside another method?

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?

Upvotes: 0

Views: 45

Answers (1)

Zalhera
Zalhera

Reputation: 629

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
}

Upvotes: 1

Related Questions