下面有一个示例方法,用于检查表是否被占用。这是我第一次进行单元测试并读取单元测试只是隔离的代码,并且应该模拟在数据库上执行的任何操作,否则它将成为集成测试。如果有人能指出我正确的方向,我不太确定怎么去嘲笑这个。
public bool isTableOccupied(string tableID)
{
bool tableOccupied = false;
try
{
connection.Open();
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = connection;
command.CommandText = "SELECT [Occupied] FROM [Table] WHERE [TableID] =@TableID";
command.Parameters.AddRange(new OleDbParameter[] {
new OleDbParameter("@TableID", tableID)
});
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader["Occupied"].ToString() == "True")
{
tableOccupied = true;
}
}
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
return tableOccupied;
}
答案 0 :(得分:1)
为了模拟单元测试的方法,您需要创建一个类应该实现的接口,例如:
public interface IRepository
{
bool IsTableOccupied(string tableId);
}
public class ExampleRepository : IRepository
{
public bool IsTableOccupied(string tableID)
{
// Your data access code goes here.
}
}
其次,您应该将Interface的实例“注入”父调用代码的方法或类,例如:
public class ExampleBusiness
{
private readonly IRepository repository;
public ExampleBusiness(IRepository repository)
{
this.repository = repository;
}
public bool IsTableOccupied(string tableId)
{
return this.repository.IsTableOccupied(tableId);
}
}
然后,您可以编写单元测试并实现模拟框架(如Moq)来模拟您的“isTableOccupied”方法,例如:
// Create mock.
var mockRepository = new Mock<IRepository>();
// Setup to return the desired mock value. In this case, return true if any string tableId is provided.
mockRepository.Setup(x => x.IsTableOccupied(It.IsAny<string>())).Returns(true);
// Call the parent method and inject the mock.
var testBusiness = new ExampleBusiness(mockRepository.Object);
// Finally, assert that the value is as expected.
Assert.IsTrue(testBusiness.IsTableOccupied("TestId");