我在栈上/从here和here中得到了一些答案,但是我很难为SqlConnection编写测试。我不想使用任何存储库,因为它是一项很小的一次性活动,它将每天运行并且不会随时更改。我虽然在界面中有下面的GetData方法
到目前为止,我的代码为:
public DataSet GetData()
{
DataSet dataSet = new DataSet("dataset");
string connectionString = "my connection string";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand("myStoredProc", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
adapter.SelectCommand = command;
adapter.Fill(dataSet);
return dataSet;
}
}
单元测试是(编写测试(:)的新功能
[TestMethod]
public void GetDevices_That_ReturnsDataSet()
{
string connectionString = "Server=tcp:localserver,1433;Initial Catalog=mydb;Persist Security Info=False;User ID=userid;Password=password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
using (ShimsContext.Create())
{
System.Data.Common.Fakes.ShimDbConnection.AllInstances.CreateCommand = (c) => {
c.ConnectionString = connectionString;
return new ShimSqlCommand();
};
ShimSqlConnection.AllInstances.ValidateConnectionForExecuteStringSqlCommand = (co, s, cmd) => { };
ShimSqlConnection.AllInstances.Open = (c) =>
{
c.ConnectionString = connectionString;
};
ShimSqlConnection.AllInstances.Close = (c) => { };
ShimSqlConnection.AllInstances.StateGet = (c) => ConnectionState.Open;
ShimSqlConnection.AllInstances.ServerVersionGet = (c) => "14.0";
ShimSqlConnection.AllInstances.ClientConnectionIdGet = (c) => It.IsAny<Guid>();
ShimSqlConnection.AllInstances.CredentialGet = (c) => new ShimSqlCredential();
ShimSqlDataReader.AllInstances.Close = (c) => { };
// Faking Adapter, from command for current instance of command
ShimSqlDataAdapter.ConstructorSqlCommand = (@this, value) => new ShimSqlDataAdapter(@this);
System.Data.Fakes.ShimDataSet.Constructor = (@this) => new System.Data.Fakes.ShimDataSet(@this)
{
// fake DataTableCollection of data set
TablesGet = () => new System.Data.Fakes.ShimDataTableCollection()
{
ItemGetInt32 = (S) =>
{
var dt = new DataTable("Devices");
dt.Columns.Add("Id");
dt.Columns.Add("Column2");
dt.Columns.Add("Column3");
dt.Rows.Add(It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<string>());
return dt;
}
},
// fake culture set for data set
LocaleSetCultureInfo = (c) => { }
};
//string commandText;
//ShimSqlCommand.AllInstances.ExecuteReader = command =>
//{
// commandText = command.CommandText;
// return new ShimSqlDataReader();
//};
// Faking Fill
System.Data.Common.Fakes.ShimDbDataAdapter.AllInstances.FillDataSetString = (a, b, c) => 0;
//Act
var dataService = new DataService();
var result = dataService.GetData();
//Assert
Assert.IsNotNull(result);
}
}
感谢您的帮助