Return to Snippet

Revision: 9609
at November 13, 2008 22:38 by rengber


Initial Code
using System;
using System.Collections.Generic;
using System.Text;
using NMock2;
using NUnit.Framework;

namespace NUnitSandbox
{
    public interface IThingInterface
    {
        int GetThingNumber(); 
    }
    public class RealThing
    {
        public int GetThingNumber()
        {
            return 13;
        }
    }

    public class ClassToBeTested
    {
        protected virtual IThingInterface GetThing()
        {
            return new RealThing() as IThingInterface;
        }
        public int WhatIsTheThingNumber()
        {
            IThingInterface iThing = GetThing();
            return iThing.GetThingNumber(); 
        }
    }

    /// <summary>
    /// This class inherits from ClassToBeTested, so it can override the Virtual Thing Factory method (GetThing).  
    /// </summary>
    [TestFixture]
    public class TestClass : ClassToBeTested
    {
        private Mockery mocks = new Mockery();

        /// <summary>
        /// This is the key.  
        /// </summary>
        protected override IThingInterface GetThing()
        {
            IThingInterface mockThing = mocks.NewMock<IThingInterface>();
            Expect.AtLeastOnce.On(mockThing).Method("GetThingNumber").Will(Return.Value(42));
            return mockThing;
        }

        [Test]
        public void TestGetThingNumber()
        {
            Assert.AreEqual(42, this.WhatIsTheThingNumber(), "Get Thing Number value should return 42 as specified by the mock.");
        }
    }
}

Initial URL


Initial Description


Initial Title
Using a Virtual Factory Method with NMock to help NUnit Testing

Initial Tags
c

Initial Language
C#