I am currently designing an API and I have run into a design issue I'm not sure how to approach.
I have a customer facing class that depends on another class from within the model. I need to test the Customer Facing class because it contains business logic.
Normally I would use Dependency Injection to handle this case, like this contrived example:
public interface IRunQuery
{
ResultObject RunQuery();
}
public class CustomerFacing
{
public CustomerFacing(IRunQuery needed)
{
Needed = needed;
}
IRunQuery Needed { get; }
public void DoSomethingForCustomer()
{
// Do some stuff.
result = Needed.RunQuery();
// Do some more stuff.
}
}
I inject a Stub of the IRunQuery interface when unit testing; it is an expensive operation. This has one enormous glaring issue, though. IRunQuery is not to be known about by the customer. They shouldn't need to know about it and the constructor for CustomerFacing should be:
public CustomerFacing() { }
How do I Unit Test CustomerFacing without injecting the dependency in the constructor?
I used "Property Injection" to solve this issue.
"IRunQuery" has a very reasonable default value. It is only in the testing case that it needs to be modified. I can define it as internal which obscures it from consumer eyes while still allowing tests to modify it before it is accessed.
public interface IRunQuery
{
ResultObject RunQuery();
}
public class CustomerFacing
{
public CustomerFacing()
{
}
private IRunQuery _needed = null;
internal IRunQuery Needed
{
get
{
if (_needed = null)
{
_needed = new StandardQuery();
}
return _needed;
}
set
{
_needed = value;
}
}
public void DoSomethingForCustomer()
{
// Do some stuff.
result = Needed.RunQuery();
// Do some more stuff.
}
}
Thanks for the help everyone.