title: Trouble mocking SqlConnection for Unit Tests
body: <p>I am calling code that I cannot change that takes in a <code>SqlConnection</code> and a <code>Transaction</code> created from that <code>SqlConnection</code>. I am attempting to mock this <code>SqlConnection</code> using Moq 4.16.1. I am getting the following error when attempting to unit test the code:</p>
  <blockquote>
  <p>Unable to cast object of type 'Castle.Proxies.IDbConnectionProxy' to type 'System.Data.SqlClient.SqlConnection'.</p>
  </blockquote>
  <p>I have wrapped the <code>SqlConnection</code> in my own wrapper to try to get this to work, but this has not helped.</p>
  <p><code>SqlConnectionWrapper</code>:</p>
  <pre><code>using System.Data;
  using System.Data.SqlClient;
  
  namespace Wrappers
  {
      public class SQLConnectionWrapper : ISQLConnectionWrapper
      {
          public string ConnectionString { get; private set; }
  
          public SQLConnectionWrapper(string connectionString)
          {
              ConnectionString = connectionString;
          }
  
          public IDbConnection Open()
          {
              return new SqlConnection(ConnectionString);
          }
      }
  }
  </code></pre>
  <p>Unit test:</p>
  <pre><code>private Mock&lt;ISQLConnectionWrapper&gt; _mockSqlConnectionWrapper;
  
  [SetUp]
  public void Setup()
  {
      _mockSqlConnectionWrapper = new Mock&lt;ISQLConnectionWrapper&gt;();
  
      var mockSQLConnection = new Mock&lt;IDbConnection&gt;();
      mockSQLConnection.SetupAllProperties();
  
      _mockSqlConnectionWrapper.Setup(x =&gt; x.Open())
          .Returns(mockSQLConnection.Object);
  }
  </code></pre>
  <p>Any help with this would be greatly appreciated.</p>