Search code examples
c#unit-testingadomd.net

How to mock a CellSet object


I got a method which converts CellSet to DataTable. Something like this:

public DataTable ConvertCellSetToDataTable(CellSet cellSet)
{
    if (cellSet == null)
    {
        return null;
    }

    var dataTable = new DataTable();
    SetColumns(cellSet, dataTable);
    WriteValues(cellSet, dataTable);
    return dataTable;
}

Now I want to write unit test for this method. Normally I would use new to create an instance, but this time I don't see any public constructor method of this class.

So, is there anyway I can

  1. mock a CellSet object
  2. and modify it's properties, such as Axes?

Rhino.Mocks is my choice for unit test framework.


Solution

  • You shouldn't mock classes/objects you don't own. In this case, because you are coupling the method(s) to CellSet you are now directly dependent to it.

    The majority of the classes in the Microsoft.AnalysisServices.AdomdClient namespace are sealed and provide no public constructors which make them very difficult to mock/fake.

    Review the CellSet class and determine what functionality you want from it. Extract the properties/methods you need and decide what you want to abstract behind a service you can control.

    Here is a simplified example of what I just explained.

    public class MyClassUnderTest {
        public DataTable ConvertCellSetToDataTable(ICellSetWrapper cellSet) {
            if (cellSet == null) {
                return null;
            }
    
            var dataTable = new DataTable();
            SetColumns(cellSet, dataTable);
            WriteValues(cellSet, dataTable);
            return dataTable;
        }
    
        private void WriteValues(ICellSetWrapper cellSet, DataTable dataTable) {
            //...assign value to datarows
        }
    
        private void SetColumns(ICellSetWrapper cellSet, DataTable dataTable) {
            //...read data from this CellSet and build data columns
        }
    }
    
    public interface ICellSetWrapper {
        //...Methods and propeties exposing what you want to use
    }
    
    public class MyCellSetWrapper : ICellSetWrapper {
        CellSet cellSet;
        public MyCellSetWrapper(CellSet cellSet) {
            this.cellSet = cellSet;
        }
        //...Implemented methods/properties
    }
    

    You can then mock the needed functionality in order to test your method with the testing framework of your choice.