title: Interfaces / Virtual for Domain Models for Unit Testing
body: <p>I am working on a .Net Core Web Application which is being Unit Tested with NUnit and Moq. Example below is very simplified for question purposes.</p>
  
  <p>I have a "purchaseOrderService" class that fetches a purchase order from the Repository and calls </p>
  
  <pre><code>purchaseOrder.Cancel();
  </code></pre>
  
  <p>before saving to the repository. The PurchaseOrder and StockItem classes are below,</p>
  
  <pre><code>public class PurchaseOrder
  {
      public int Id { get; set; }
  
      public List&lt;StockItem&gt; StockItems { get; set; }
  
      public PurchaseOrderStatus Status { get; private set; }
  
      public void Cancel()
      {
          Status = PurchaseOrderStatus.Cancelled;
          foreach(var stockItem in StockItems)
              stockItem.Cancel();
      }
  }
  
  public class StockItem
  {
      public int Id { get; set; }
  
      public StockItemStatus Status { get; private set; }
  
      public void Cancel()
      {
          Status = StockItemStatus.Cancelled;
      }
  }
  </code></pre>
  
  <p>In the unit test for my purchaseOrder.Cancel method, i wanted to Mock the stockItem, so I could verify that the cancel cancel method was called once for every stockItem inside the purchase order.</p>
  
  <p>I would typically achieve this with something like.</p>
  
  <pre><code>Mock&lt;StockItem&gt; mockSI = new Mock&lt;StockItem&gt;();
  mockSI.Setup(x =&gt; x.Cancel());
  mockSI.Setup( x=&gt; x.Cancel(), Times.Once);
  </code></pre>
  
  <p>However, the domain model isn't exposed as an interface and the Cancel method is not virtual so the Cancel method cannot be overridden for the purposes of a Mock.</p>
  
  <p>This leaves me with 3 options</p>
  
  <ol>
  <li><p>Make the cancel method Virtual - This seems like a terrible idea and exposes it to being overridden at unwanted times.</p></li>
  <li><p>Make an interface for the domain model needing to be mocked - This seems excessive as i would be making the interface for testing only without plan to have any other class inherit the interface and on classes I have full control over. Multiple posts on StackOverflow say that interfaces for Domain Models without good reason is bad practice.</p></li>
  </ol>
  
  <p>for example,
  <a href="https://stackoverflow.com/questions/29253606/interfaces-for-rich-domain-models">Interfaces for Rich Domain Models</a></p>
  
  <ol start="3">
  <li>Treat this as more of an integration test and test the 2 classes working together</li>
  </ol>
  
  <p>At the moment I'm leaning towards making the StockItem class implement an interface. What would you recommend?</p>