2016-04-07 127 views
0

我有一个示例方法,它检查表是否被占用。这是我第一次进行单元测试,并且认为单元测试只是单独编码,并且应该嘲笑在数据库上执行的任何操作,否则它将成为集成测试。我不太清楚如何去嘲笑这个,如果任何人都能指出我的正确方向。如何模拟连接到MS Access数据库的方法

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] [email protected]"; 
       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; 
} 

回答

1

为了嘲笑的方法进行单元测试,你将需要建立一个类应该实现一个接口,例如:

public interface IRepository 
{ 
    bool IsTableOccupied(string tableId); 
} 

public class ExampleRepository : IRepository 
{ 
    public bool IsTableOccupied(string tableID) 
    { 
     // Your data access code goes here. 
    } 
} 

其次,你应该再“注入”实例接口到父调用代码的方法或类,例如:

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的,模拟出哟例如:ur“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"); 
+0

如果此方法不与任何其他方法交互,您认为这是否值得?所以它的返回并不妨碍我单元测试其他方法。我应该直接进行这种方法的集成测试并跳过单元测试吗? – user5467760

+0

所有我觉得嘲笑这种方法做的是改变它'布尔isTableOccupied(“tableID”){返回true}'。有没有什么意思?' – user5467760

+0

它当然取决于每一个独特的场景 - 它可能不值得你的情况,但通常好的做法是抽象出接口后面的数据访问代码。代码将在未来为您自己和其他人提供更好的可维护性和可测试性。我给出的返回true的例子只是一个例子。你可以设置模拟返回不同的值,取决于提供的特定ID。正如我所说,每个场景都是独一无二的。我只会说,只有测试它是否增加了价值并声称有价值的东西,通常集成测试可能会更有用。 – abrown

相关问题