我有这个查询数据库的代码。我想将实际的数据库代码放入一个单独的类中,以便我可以在其他地方重用它。这将只留下PassResult值的实际读取,因此我可以在不运行SQL代码的情况下对代码进行单元测试。我无法找到关于如何使这种代码单元可测试的参考。有人可以帮忙吗?
using System;
using System.Data;
using System.Data.SqlClient;
namespace CS_UI_Final_Inspection
{
public class CalibrationTestCheck
{
// declare the variables
private bool _calibrationTestPass = false;
private string _connectionString = string.Empty;
public bool CheckCalibrationTestResults(string serialNumber, IDeviceInfo deviceInfo, string mapID)
{
// get database location
DhrLocationPull dhrLocation = new DhrLocationPull();
_connectionString = dhrLocation.PullDhrLocation();
// build the query
SqlConnection calibrationCheckConnection = new SqlConnection(_connectionString);
SqlCommand calibrationCheckCommand = new SqlCommand("[MfgFloor].[GetLatestTestResultsForDeviceByTestType]",
calibrationCheckConnection);
// build the stored proc
calibrationCheckCommand.CommandType = CommandType.StoredProcedure;
calibrationCheckCommand.Parameters.Add(new SqlParameter("@SerialNumber", serialNumber));
calibrationCheckCommand.Parameters.Add(new SqlParameter("@DeviceTypeID", mapID));
calibrationCheckCommand.Parameters.Add(new SqlParameter("@TestDataMapTypeID", "C"));
calibrationCheckCommand.Connection.Open();
SqlDataReader calibrationCheckReader = calibrationCheckCommand.ExecuteReader();
// is there data?
if (calibrationCheckReader.HasRows)
{
// read the data
calibrationCheckReader.Read();
try
{
_calibrationTestPass = (bool) calibrationCheckReader["PassResult"];
}
catch (InvalidOperationException)
{
// means last element was not filled in
}
finally
{
// close refs
calibrationCheckReader.Close();
calibrationCheckCommand.Connection.Close();
calibrationCheckConnection.Close();
calibrationCheckReader.Dispose();
calibrationCheckCommand.Dispose();
calibrationCheckConnection.Dispose();
}
}
return _calibrationTestPass;
}
}
}
答案 0 :(得分:0)
Roy Oscherov是一个很好的资源。 Roy Oscherov写了一本名为"单元测试艺术的伟大着作"。罗伊的网站可以在这里找到:http://osherove.com/