This code creates a mock database connection and a data command that are used by our database class during the test. The SetExpectedExecuteCalls method works in conjunction with the Verify method to ensure that the InsertNames method of the database class does in fact execute one (and only one) command. If our InsertNames function were to perform multiple insert commands then we could simply modify this number to reflect the expected number of executions.
Because our database test class will require a mock connection for each test, we can place the mock connection object in the SetUp attribute of the test as follows.
[TestFixture]
public class TestSampleFixture
{
private MockDbConnection cnn;
[SetUp]
public void SetUp()
{
cnn = new _MockDbConnection();
}
[TearDown]
public void TearDown()
{
cnn.Verify();
}
[Test]
public void TestInsertRecords()
{
MockCommand cmd = new _ MockCommand();
cnn. _ SetExpectedCommand(cmd);
cmd.SetExpected _ CommandText(DatabaseClass.INSERTION_SQL);
cmd.SetExpected _ ExecuteCalls(1);
DatabaseClass _ myDBClass = new DatabaseClass(cnn);
myDBClass. _InsertNames();
}
}
Notice that we no longer need to call the Verify method of the command object in each test. Instead, the Verify method of the connection object can be invoked during the TearDown phase of each test. Note also that it is possible to work with transactions and stored procedures as shown here.
[Test]
public void TestDeleteRecords()
{
MockCommand cmd = new _MockCommand();
cnn.SetExpectedCommand(cmd);
cmd.SetExpectedCommandText_ (DatabaseClass.DELETION_SQL);
cmd.CommandType = System.Data. _ CommandType.StoredProcedure;
cmd.SetExpectedExecuteCalls(3);
DatabaseClass myDBClass = new _ DatabaseClass(cnn);
MockTransaction txn = _(MockTransaction) cmd.Transaction;
txn.ExpectCommitCall(true);
myDBClass.DeleteNames();
}