title: Test a recursive Function with Moq
body: <p>I have a recursive method i have tried to simply it for the sake of readability as it is a messy method.</p>
  
  <p>I would like to get 100% coverage of the recursive method. I am struggling to setup the mock that will go through the recursion twice. then exit. I think i would need to use call back and not returns, I am not 100% sure.</p>
  
  <pre><code>    [TestMethod]
      public void TestRecursiveLoop()
      {
        var rootList = new List&lt;MyObject&gt; { new MyObject { Id = 999, ParentId = 1000 }, new MyObject { Id = 1000 } };
        var myObject = new MyObject { Id = 999 };
  
        var myMock = new Mock&lt;IDBCLASS&gt;();
        myMock.Setup(o =&gt; o.GETBYType(It.IsAny&lt;Expression&lt;Func&lt;MyObject, bool&gt;&gt;&gt;()))
          .Returns((Expression&lt;Func&lt;ShareholderTransaction, bool&gt;&gt; predicate) =&gt;
          {
            return new List&lt;MyObject&gt;().Where(o =&gt; o.ParentId == myObject.Id).ToList();
          });
        // ?????????? not sure if this is correct
        var testRecursion = new TestRecursion(myMock.Object);
        testRecursion.Recursive(999, rootList);
  
      }
    }
  
    public class TestRecursion
    {
      private IDBCLASS dbClass;
  
      public TestRecursion(IDBCLASS dbClass)
      {
        this.dbClass = dbClass;
      }
  
      public void Recursive(int id, List&lt;MyObject&gt; list)
      {
        var parentObject = this.dbClass.GETBYType&lt;MyObject&gt;(x =&gt; x.ParentId == id).FirstOrDefault();
  
        if (parentObject == null)
        {
          return;
        }
  
        list.Add(parentObject);
        Recursive(parentObject.Id, list);
      }
    }
  
    public class MyObject
    {
      public int ParentId { get; set; }
  
      public int Id { get; set; }
  
    }
  
    public class DBCLASS : IDBCLASS
    {
  
      public List&lt;T&gt; GETBYType&lt;T&gt;(Expression&lt;Func&lt;T, bool&gt;&gt; p) where T : class
      {
        // return something from DB;
      }
  
    }
    public interface IDBCLASS
    {
      List&lt;T&gt; GETBYType&lt;T&gt;(Expression&lt;Func&lt;T, bool&gt;&gt; p) where T : class;
    }
  </code></pre>