Ayo Adesina

Ayo Adesina

  • NA
  • 1
  • 2.6k

TDD With Moq, Test passing when is shouldn't.

Apr 19 2013 6:49 AM
Hey Guys,

I am just starting out with Moq and Nunit and I was following along with an example in a book: Professional Test Driven Development with C#: Developing Real World Applications with TDD (Wrox Professional Guides)  and I am not getting the same result and I just thought someone here might be able to explain why..

The example has a class(LongRunningLibrary) with a method called(RunForALongTime)  that mimics a database call that takes x seconds to complete.

    public class LongRunningLibrary : ILongRunningLibrary
    {
        public string RunForALongTime(int interval)
        {
            var timeToWait = interval*1000;
            Thread.Sleep(timeToWait);
            return string.Format("Waited {0} Seconds", interval);

        }
    }

     [TestFixture]
    public class LongRunningTest
    {
        private ILongRunningLibrary _longRunningLibrary;

        [SetUp]
        public void SetupForTest()
        {
            _longRunningLibrary = new LongRunningLibrary();
        }

        [Test]
        public void TestLongRunningLibrary()
        {
            const int interval = 35;
            var result = _longRunningLibrary.RunForALongTime(interval);
            var output = string.Format("Return from method was: {0}", result);
            Debug.WriteLine(output);

        }
    }


Then it shows you how you can mock this class using moq, but explains that this should fail becuase you have not specified an implementation for the method:

    [TestFixture]
    public class LongRunningTestUsingMock
    {
        private Mock<ILongRunningLibrary> _longRunningLibrary;

        [SetUp]
        public void SetupForTest()
        {
           _longRunningLibrary = new Mock<ILongRunningLibrary>();
        }

        [Test]
        public void TestLongRunningLibrary2()
        {
            const int interval = 30;
            var result = _longRunningLibrary.Object.RunForALongTime(interval);
            var output = string.Format("Return from method was: {0}", result);
            Debug.WriteLine(output);
        }
    }


But When I run this it passes on my machine it passes, why? It dosn't take 30 seconds to run so I know its not running the actually method 'RunForALongTime' but it does pass, any one know why this is the case, is it becuase this book might be using a slightly older version of Moq?

Would be nice to know why?

Thanks in advance.

Ayo