Using a Virtual Factory Method with NMock to help NUnit Testing


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



Copy this code and paste it in your HTML
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using NMock2;
  5. using NUnit.Framework;
  6.  
  7. namespace NUnitSandbox
  8. {
  9. public interface IThingInterface
  10. {
  11. int GetThingNumber();
  12. }
  13. public class RealThing
  14. {
  15. public int GetThingNumber()
  16. {
  17. return 13;
  18. }
  19. }
  20.  
  21. public class ClassToBeTested
  22. {
  23. protected virtual IThingInterface GetThing()
  24. {
  25. return new RealThing() as IThingInterface;
  26. }
  27. public int WhatIsTheThingNumber()
  28. {
  29. IThingInterface iThing = GetThing();
  30. return iThing.GetThingNumber();
  31. }
  32. }
  33.  
  34. /// <summary>
  35. /// This class inherits from ClassToBeTested, so it can override the Virtual Thing Factory method (GetThing).
  36. /// </summary>
  37. [TestFixture]
  38. public class TestClass : ClassToBeTested
  39. {
  40. private Mockery mocks = new Mockery();
  41.  
  42. /// <summary>
  43. /// This is the key.
  44. /// </summary>
  45. protected override IThingInterface GetThing()
  46. {
  47. IThingInterface mockThing = mocks.NewMock<IThingInterface>();
  48. Expect.AtLeastOnce.On(mockThing).Method("GetThingNumber").Will(Return.Value(42));
  49. return mockThing;
  50. }
  51.  
  52. [Test]
  53. public void TestGetThingNumber()
  54. {
  55. Assert.AreEqual(42, this.WhatIsTheThingNumber(), "Get Thing Number value should return 42 as specified by the mock.");
  56. }
  57. }
  58. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.