To Constructor Inject Or Not With TDD?
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:
- 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.
- 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)
{
...
}
}
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.
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.
精彩评论