David
David

Reputation: 19687

Fakes: Downcast SqlConnection to DbConnection

How can I get this fake to work? I'd expect the last Assert to pass.

System.Data.fakes

<Fakes xmlns="http://schemas.microsoft.com/fakes/2011/">
  <Assembly Name="System.Data" Version="4.0.0.0"/>
</Fakes>

Test.cs

using System.Data.Common;
using System.Data.SqlClient;
using System.Data.SqlClient.Fakes;
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class FakeTest
{
    [TestMethod]
    public void DownCast()
    {
        using (ShimsContext.Create())
        { 
            SqlConnection sqlCn = new ShimSqlConnection 
            { 
                CreateCommand = () => new ShimSqlCommand(), 
                CreateDbCommand = () => new ShimSqlCommand() 
            };

            Assert.IsNotNull(sqlCn.CreateCommand());

            DbConnection dbCn = sqlCn;

            Assert.IsNotNull(dbCn.CreateCommand()); // How can I make this pass?
        }
    }
}

Upvotes: 1

Views: 425

Answers (1)

David
David

Reputation: 19687

Adding the line new ShimDbConnection(sqlCn) { CreateCommand = () => new ShimSqlCommand() }; after the initial setup allows the test to pass.

using System.Data.Common;
using System.Data.Common.Fakes;
using System.Data.SqlClient;
using System.Data.SqlClient.Fakes;
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class FakeTest
{
    [TestMethod]
    public void DownCast()
    {
        using (ShimsContext.Create())
        {
            SqlConnection sqlCn = new ShimSqlConnection
            {
                CreateCommand = () => new ShimSqlCommand(),
                CreateDbCommand = () => new ShimSqlCommand()
            };
            new ShimDbConnection(sqlCn) { CreateCommand = () => new ShimSqlCommand() }; // Adding this line, the test passes.

            Assert.IsNotNull(sqlCn.CreateCommand());

            DbConnection dbCn = sqlCn;

            Assert.IsNotNull(dbCn.CreateCommand());
        }
    }
}

Upvotes: 1

Related Questions