Reputation: 11673
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:
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)
{
...
}
}
Upvotes: 3
Views: 328
Reputation: 48583
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.
Upvotes: 1
Reputation: 2789
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.
Upvotes: 1