in C#

Unit Testing ObjectResult

I came across an interesting scenario where I wanted to unit test an imported function in the Entity Framework. The initial problem is that an imported function generates code like this:

1
2
3
4
5
public virtual ObjectResult<MyObject> GetData()
        {
   
            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<MyObject>("GetData");
        }

The key method here is the results are returned as the ObjectResult object which 1) cannot be mocked (using RhinoMocks) because it’s sealed. There are no constructors available to create concrete instances of the object. So the best solution I can come up with is to create a new interface and create two classes that implement the interface, one for the real application and one for unit testing. From here, the unit testing class which has the interface can return anything it likes i.e. fake objects while the other class can call the function import method and return the results.

Firstly, I create the interface

1
2
3
4
5
6
public partial interface IExtendedEntities
    {
       
        IEnumerable<MyObject> GetDataWrapper();

    }

Secondly, I create the class that will use this interface for the real application.

1
2
3
4
5
6
7
public partial class MyClassReal : DbContext, IExtendedEntities
    {
        public IEnumerable<MyObject> GetDataWrapper()
        {
            return this.GetData().AsEnumerable();
        }
    }

Thirdly, create the class that uses the interface for unit testing

1
2
3
4
5
6
7
public partial class MyClassFake : DbContext, IExtendedEntities
    {
        public IEnumerable<MyObject> GetDataWrapper()
        {
            return Builder<MyObject>.CreateListOfSize(10).Build();
        }
    }

When I’m implementing the logic, I can inject (using nInject) an object of the interface IExtendedEntities and call GetDataWrapper();

When unit testing, I can create a new MyClassFake object and return a list of test data. This gives me the control to create a test case of specific test data to be put through the method that gets called to return a set of results from the Imported Function.