Mocking

Mocking, or intercepting, in MicroDal is now possible, via the BeforeDbResourceCall event of the DataSession object as described here: Unittesting.

To minimize the code in unittests, and to make them more structured. I have made this mockery class with a convinient fluent interface:

using System;
using MicroDal;
using System.Data.Common;

namespace TGBackendTest
{
    public class MDTestMockery : IRecorder, IIntercepter
    {
        private Action _doOnPlayback = () => { };
        private Action<string, DbParameterCollection> _doOnInterception = (sql, pc) => { };

        public IIntercepter Record(Action action)
        {
            this._doOnPlayback = action;
            return this;
        }

        public void Playback()
        {
            EventHandler<DbResourceCallEventArgs> handler = (s, ea) => _doOnInterception(ea.SqlQuery, ea.Parameters);
            MicroDal.DataSession.Current.BeforeDbResourceCall += handler;
            _doOnPlayback();
            MicroDal.DataSession.Current.BeforeDbResourceCall -= handler;
        }

        public IRecorder Intercept(Action<string, DbParameterCollection> doOnInterception)
        {
            this._doOnInterception = doOnInterception;
            return this;
        }
    }

    public interface IRecorder : IPlayback
    {
        IIntercepter Record(Action action);
    }
    public interface IIntercepter : IPlayback
    {
        IRecorder Intercept(Action<string, DbParameterCollection> doOnInterception);
    }

    public interface IPlayback
    {
        void Playback();
    }


All You have to do is to initialize the MDTestMockery class, and arrange the test:
[TestClass]
public class IdraetTest
{
    MDTestMockery mock;
    [TestInitialize]
    public void Init()
    {
        mock = new MDTestMockery();
    }

    [TestMethod]
    public void Load_CaleDALWithParam()
    {
        int expected=123; object actual=-1;

        mock
            .Intercept((sql, pc) =>
            {
                // code to hook into MD
                pc.TryGet("@id", out actual);
            })
            .Record(() =>
            {
                // The action to perform - SUT
                Idraet.Load(expected);
            })
            .Playback(); // Run the test

        Assert.AreEqual(expected, actual);
    }
}


As You can se, we are using the Record / Playback pattern.

Last edited Feb 17, 2011 at 7:12 AM by TheIMan, version 4