简体   繁体   中英

How to mock a method connecting to an MS Access database

I have an example method below, which checks whether a table is occupied. It's my first time doing unit tests and read that a unit test is code only in isolation and that any action performed on a database should be mocked out, otherwise it becomes an integration test. I'm not quite sure how to go about mocking this out though, if anyone can point me in the right direction.

 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;
}

In order to mock a method out for unit testing you will need to create an Interface which your class should implement, for example:

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

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

Secondly, you should then "inject" the instance of the Interface into the method or class of the parent calling code, for example:

public class ExampleBusiness
{
    private readonly IRepository repository;

    public ExampleBusiness(IRepository repository)
    {
        this.repository = repository;
    }

    public bool IsTableOccupied(string tableId)
    {
        return this.repository.IsTableOccupied(tableId);
    }
}

You can then write unit tests and implement a mocking framework, such as Moq, to mock out your "isTableOccupied" method, for example:

// 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM