I recently discovered a rather annoying limitation in Moq: you cannot setup expectations on the ToString method. For a good discussion of the issue, check out Sean’s post. His solution was to add ToString explicitly to the interface you are mocking, but I don’t want to dirty up my interfaces unnecessarily. Fortunately, Moq does allow you to create mocks that implement multiple interfaces, so you could move the ToString method to a dummy interface, and use Mock<T>.As to setup expectations on the dummy interface. That’s the approach I took, but I wrapped it up in a nice extension method:
public static class MoqExtensions { public static ISetup<IToStringable, string> SetupToString<TMock>(this Mock<TMock> mock) where TMock : class { return mock.As<IToStringable>().Setup(m => m.ToString()); } //Our dummy nested interface. public interface IToStringable { /// <summary> /// ToString. /// </summary> /// <returns></returns> string ToString(); } }
Now I can setup expectations on ToString by simply using:
[Test] public void ExpectationOnToStringIsMet() { var widget = new Mock<IWidget>(); widget.SetupToString().Returns("My value").Verifiable(); Assert.That(widget.Object.ToString(), Is.EqualTo("My value")); widget.Verify(); }
Do you have a spam problem here; I also use Blog Engine, and I was speculating about your situation; we have developed some great practices and we would like to exchange techniques with others, please Email me if interested.
Excellent post.I have bookmarked it already. Take care, Osman.
Superb article.Ive bookmarked it already. Best regards, Vikas.