How to unittest business objects

Business objects which are using MD, is hard to test. You cant mock MD with Rhino mocks, because DataSession is sealed, and it is cumbersome to write wrappers for all the calls.
As of CS #55078 it is now possible to hook into the Microdal object. All You have to do, is to write an eventhandler for the
BeforeDbResourceCall event. It is raised every time there is a call to one of the public methods (Fetch, FetchOne, FetchScalar or Execute)

Example

You have a class in the Business assembly:
public class Person{
   public void Delete(string name){
    MDSession.Current.Execute("DELETE Person WHERE name = @name", name);
   }
}

To test the 'Delete' method, You should assert that MD is called with the proper parameter - it can be done like this:
        [TestMethod]
        public void TestDelete()
        {
            string expected = "Adam"; object actual = null;
            var sut = new Person();

            DataSession.Current.BeforeDbResourceCall += (s, ea) =>
            {
                ea.Parameters.TryGet("@name", out actual);
            };

            sut.Delete(expected);
            Assert.AreEqual(expected, actual);
        }

As You can see: The method is not only testing the value, but also the name of the DbParameter.
This goes without even touching a database.
We have made a mockery class for this kind of tests: Test Mock

Last edited Oct 10, 2010 at 7:17 AM by TheIMan, version 6