2017-10-12 68 views
1

我怎樣才能讓這個假工作?我希望最後的斷言能夠通過。Fakes:Downcast SqlConnection to DbConnection

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? 
     } 
    } 
} 

回答

1

添加在初始安裝後的線new ShimDbConnection(sqlCn) { CreateCommand =() => new ShimSqlCommand() };允許測試通過。

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()); 
     } 
    } 
}