Using NMock to Create an IDataReader for Testing Data Access Methods


/ Published in: C#
Save to your folder(s)

Shows how to mock the Object["CollectionItemName"] syntax.


Copy this code and paste it in your HTML
  1. public class TransactionStore
  2. {
  3. public virtual IDataReader GetReader(SqlCommand cmd)
  4. {
  5. return cmd.ExecuteReader();
  6. }
  7.  
  8. public decimal GetAvailableBalance(int custNumb)
  9. {
  10. decimal retVal = 0.00M;
  11. using (SqlConnection sqlConnection = new SqlConnection(_dbConnection))
  12. {
  13. sqlConnection.Open();
  14. using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
  15. {
  16. sqlCommand.CommandType = CommandType.StoredProcedure;
  17. sqlCommand.CommandText = "dbo.GetCustomerBalance";
  18. sqlCommand.Parameters.AddWithValue("CustomerID", custNumb);
  19. using (IDataReader dr = GetReader(sqlCommand))
  20. {
  21. if (dr != null)
  22. {
  23. dr.Read();
  24. retVal = Convert.ToDecimal(dr["AvailableBalance"]);
  25. }
  26. }
  27. }
  28. }
  29. return retVal;
  30. }
  31. }
  32.  
  33.  
  34. [TestFixture]
  35. public class IMTTests : TransactionStore
  36. {
  37. Mockery mocks = new Mockery();
  38. IDataReader idr = null;
  39.  
  40. public override IDataReader GetReader(SqlCommand cmd)
  41. {
  42. Expect.AtLeastOnce.On(idr).Method("Read").Will(Return.Value(true));
  43. Expect.AtLeastOnce.On(idr).Method("Dispose");
  44. return idr;
  45. }
  46.  
  47. [Test]
  48. public void TestAvailableBalance()
  49. {
  50. idr = (IDataReader)mocks.NewMock(typeof(IDataReader));
  51. Expect.AtLeastOnce.On(idr).Get["AvailableBalance"].Will(Return.Value(42.00M));
  52. Decimal amount = this.GetAvailableBalance(12345);
  53. Assert.AreEqual(42.00M, amount);
  54. }
  55. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.