title: Mocking inherited class with Moq
body: <p>I have some Web API methods that I want to write unit tests for. They need database access, so, naturally, I wanted to Moq that part.</p>
  
  <p>The storage classes are accessed via an interface, and the class that implements the API method inherits the interface. What I don't know is how to mock is the inherited interface in a unit test.</p>
  
  <pre><code>public class CreateWishList : APIAccess
  {
      public long CreateWishListV1(long userId, string wishListName)
      {
          // Do stuff like
          long result = Storage.CreateWishList(userId, wishListName);
  
          return result;
      }
  }
  
  public class APIAccess
  {
      protected IStorage Storage { get; private set; }
  
      public APIAccess() : this(new APIStorage()) { }
  
      public APIAccess(IStorage storage)
      {
          Storage = storage;
      }
  }
  
  public interface IStorage
  {
      long CreateWishList(long userId, string wishListName);
  }
  </code></pre>
  
  <p>So, I want to unit test the <code>CreateWishListV1(...)</code> method, and to do that without database access, I need to mock what <code>Storage.CreateWishList(...)</code> returns. How do I do that?</p>
  
  <p>UPDATE:</p>
  
  <p>I'm trying something like this:</p>
  
  <pre><code>[Test]
  public void CreateWishListTest()
  {
      var mockAccess = new Mock&lt;APIAccess&gt;(MockBehavior.Strict);
      mockAccess.Setup(m =&gt; m.Device.CreateWishList(It.IsAny&lt;long&gt;(), It.IsAny&lt;string&gt;())).Returns(123);
  
      var method = new CreateWishList();
      method.Storage = mockAccess.Object;
  
      long response = method.CreateWishListV1(12345, "test");
  
      Assert.IsTrue(response == 123, "WishList wasn't created.");
  }
  </code></pre>
  
  <p>Had to change the <code>Storage</code> property on <code>APIAccess</code> to public as well.</p>