问题
I have the following tightly coupled database access class (repository), that is hard to unit test:
class EmployeesRepository : IEmployeeRepository ...
public IEnumerable<Employee> GetAllEmployees()
{
List<Employee> list = new List<Employee>();
try
{
string connectionString = _secureConfig.Value.MyDbSetting;
string sql = "select id, firstname, lastname, entrydate, email from empoyees";
using SqlConnection connection = new SqlConnection(connectionString);
using SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
using SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
list.Add(new Employee
{
Id = reader.GetString(0),
FirstName = reader.GetString(1),
LastName = reader.GetString(2),
EntryDate = reader.GetDateTime(3),
Email = (reader.IsDBNull(4) ? null : reader.GetString(4))
});
}
}
catch (Exception ex)
{
_log.LogError(ex, "An error is caught when getting all employees");
}
return list;
}
sometimes the same code uses command.ExecuteNonQuery()
, there are also sometimes connection.BeginTransaction()
...
My question is what is the pattern should be used to decouple this class into logical units, in order to facilitate integration testing.
来源:https://stackoverflow.com/questions/65599782/how-to-break-the-database-access-class-of-a-repository