Hi I am trying to learn about the moq framework but I seem to fail to understand a simple concept.Here is the code I am testing:
public interface ILongRunningLibrary {
string RunForALongTime(int interval);
}
public class LongRunningLibrary : ILongRunningLibrary {
public string RunForALongTime(int interval) {
var timeToWait = interval * 1000;
Thread.Sleep(timeToWait);
return string.Format("Waited {0} seconds ", interval);
}
}
And here are my tests:
private Mock<ILongRunningLibrary> _longRunningLibrary;
[SetUp]
public void SetupForTest() {
_longRunningLibrary = new Mock<ILongRunningLibrary>();
}
[Test]
public void TestLongRunningLibrary() {
const int interval = 30;
_longRunningLibrary.Setup(lrl => lrl.RunForALongTime(30))
.Returns("This method has been mocked!");
var result = _longRunningLibrary.Object.RunForALongTime(interval);
Debug.WriteLine("Return from method was '{0}'", result);
}
From what I understood from the book I am reading is that this method should return on NUnit console “This method has been mocked”.But in my case the test passes and it returns nothing.
Even if I remove :
_longRunningLibrary.Setup(lrl => lrl.RunForALongTime(30))
.Returns("This method has been mocked!");
The test still passes and on the console nothing is printed.
Why is it that “This method has been mocked” is not returned on NUnit console?
Your first example runs just fine. I think your test runner fails to call Debug.WriteLine. I replaced it with Console.WriteLine and I got the correct output.
When you removed the Setup call in your second example, the mock will return the default value(which is null) because it uses Loose behavior. When you call Debug.WriteLine with a null parameter it doesn’t throw an exception so your test passes.
It is a good practice to use StrictBehavior generally.
Now it will throw an exception because you do not have any setups for RunForALongTime method.