Sunday, 26 August 2012
0 comments

Rhino Mocking "out" parameters

Sunday, 26 August 2012 01:19
Last week, I was stumped by a block of Rhino Mocks code. Here's a stripped down version of it:
    [TestClass]
    public class DataHelperTests
    {
        private MockRepository _mocks = new MockRepository();

        [TestMethod]
        public void TestSubstString()
        {
            var dp = _mocks.StrictMock<IDataProvider>();
            dp.Expect(p => p.TryGetData(Arg.Is("ERR001"), out Arg<string>.Out("This is a test error message.").Dummy)).Return(true);
            var result = DataHelper.SubstString(dp, "Error ERR001: ${ERR001}");
            Assert.AreEqual("Error ERR001: This is a test error message.", result);
        }
    }

The above unit test uses Rhino Mocks' method for mocking out parameters. DataHelper is a helper class which manipulates IDataProvider object. Just to give you some context without going into the gory details about DataHelper's implementation, the SubstString() method essentially performs a series of key replacements based on value retrieved from a database, supported by IDataProvider.TryGetData(). The method TryGetData() returns a boolean value indicating whether or not it was successful in retrieving a value for the key.

This is where things get tricky. The above test code would fail.

It failed because the Expect() statement had no effect...until you add this all-important ReplayAll().

Here's the test code in its entirety:

    [TestClass]
    public class DataHelperTests
    {
        private MockRepository _mocks = new MockRepository();

        [TestMethod]
        public void TestSubstString()
        {
            var dp = _mocks.StrictMock<IDataProvider>();
            dp.Expect(p => p.TryGetData(Arg.Is("ERR001"), out Arg<string>.Out("This is a test error message.").Dummy)).Return(true);
            _mocks.ReplayAll();
            var result = DataHelper.SubstString(dp, "Error ERR001: ${ERR001}");
            Assert.AreEqual("Error ERR001: This is a test error message.", result);
        }
    }

Truthbetold, I just installed Alex Gorbatchev’s SyntaxHighlighter script on this blog. This post is just an excuse for me to test out the script. Kudos to Matt Ball for the detailed install instructions for Blogger.

0 comments :

Post a Comment

 
Toggle Footer
Top