code_junkie

Verifying protected abstract methods are called using Moq

Nov 13th, 2011
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. public class TestBase
  2. {
  3. public bool runMethod1 { get; set; }
  4.  
  5. public void BaseMethod()
  6. {
  7. if (runMethod1)
  8. ChildMethod1();
  9. else
  10. ChildMethod2();
  11. }
  12.  
  13. protected abstract void ChildMethod1();
  14. protected abstract void ChildMethod2();
  15. }
  16.  
  17. public class ChildTest : TestBase
  18. {
  19. protected override void ChildMethod1()
  20. {
  21. //do something
  22. }
  23.  
  24. protected override void ChildMethod2()
  25. {
  26. //do something completely different
  27. }
  28.  
  29. }
  30.  
  31. [Test]
  32. public BaseMethod_should_call_correct_child_method()
  33. {
  34. TestBase testBase;
  35.  
  36. //todo: get a mock of TestBase into testBase variable
  37.  
  38. testBase.runMethod1 = true;
  39.  
  40. testBase.BaseMethod();
  41.  
  42. //todo: verify that ChildMethod1() was called
  43.  
  44. }
  45.  
  46. //expect that ChildMethod1() will be called once. (it's protected)
  47. testBaseMock.Protected().Expect("ChildMethod1")
  48. .AtMostOnce()
  49. .Verifiable();
  50.  
  51. ...
  52.  
  53. //make sure the method was called
  54. testBase.Verify();
  55.  
  56. [Test]
  57. public BaseMethod_should_call_correct_child_method()
  58. {
  59. //strict mocks will make sure all expectations are met
  60. var testBaseMock = new Mock<TestBase>(MockBehavior.Strict);
  61.  
  62. //expect that ChildMethod1() will be called once. (it's protected)
  63. testBaseMock.Protected().Expect("ChildMethod1")
  64. .AtMostOnce();
  65.  
  66. var testBase = testBaseMock.Object;
  67.  
  68. testBase.runMethod1 = true;
  69. testBase.BaseMethod();
  70.  
  71. //make sure the method was called
  72. testBase.VerifyAll();
  73. }
Add Comment
Please, Sign In to add comment