views:

70

answers:

2

I have a method that I'm trying to unit test that uses a query object, I would like to Stub this query object for my unit tests. This query object does has a dependency (UnitOfWork). I am using a IOC/DI container to instantiate my objects in the app. However I DO NOT want to use the container while TDD. The way I see it is I have 2 options:

  1. Add the query object to the method's class as a field or property and inject it as a ctor argument. This however does not feel right as this 1 method is the only method that will use it, and if I did ever have to add a second method that did use this query object, the object would have to be re-instantiated or Reset after each use.
  2. Add the query object to the method's signature. Smell?

Are there other options or patters for this? Or am I approaching it wrong?

Here is some pseudo code:

Option #1

public class OrdersController
{
            public OrdersController(IOrderQuery query)
            {
                this.query = query;
            }

            private readonly IOrderQuery query;

            public Queryable<Order> OrdersWaiting()
            {
                var results = query(...);
                ...
            }
}

Option #2

public class OrdersController
{
            public Queryable<Order> OrdersWaiting(IOrderQuery query)
            {
                var results = query(...);
                ...
            }
}

And my query object

public class OrderQuery : IOrderQuery
{
            public OrderQuery(IUnitOfWork unitOfWork)
            {
                ...
            }
}
+1  A: 

Definitely prefer option 1 over option 2. Seems like it would be the IOC container's responsibility to instantiate/have knowledge of the query object. The caller shouldn't have to know the details of how/where OrdersWaiting gets its data.

With option 2, not only does the caller need to get the instance of the controller, it needs to get the instance of the query object, which probably should be beyond the caller's visibility.

_rusty
The problem with Option 1 is what if I need to use the query object in a second method? I would have to remember to re-new it, or Reset() it somehow or make a call to the container to get a new one. Basically what I am saying it I would need to re-instantiate it with every use.
mxmissile
+1  A: 

if I did ever have to add a second method that did use this query object, the object would have to be re-instantiated or Reset after each use.

If this is what's stopping you from using constructor injection here, consider injecting an IOrderQueryFactory instead.

Jeff Sternal
Nice, one of those aha! moments for me. thank you!
mxmissile