Reputation: 5333
I am trying to refactor some classes in a project to make them testable using interfaces and dependency injection. But I struggle with the following:
public interface IInterfaceA
{
void SomePublicMethod();
}
public class ConcreteObject : IInterfaceA
{
public void SomePublicMethod() { ... }
public void SomeOhterMethod() { ... }
public void YetAnotherMethod() { ... }
}
public class AnotherConcreteObject
{
private IInterfaceA _myDependency;
public AnotherConcreteObject( IInterfaceA myDependency )
{
_myDependency=myDependency;
}
}
So far everything is fine, pretty standard code. AnotherConcreteObject needs to call SomeOtherMethod, but I don't want other classes (e.g. in a different assembly) to be able to call SomeOtherMethod. So externally SomePublicMethod should be visible, but SomeOtherMethod should not be. Only instances of AnotherConcreteObject should be able to call SomeOtherMethod. SomeOtherMethod will e.g. set a internal property which is used later by YetAnotherMethod to determine what should happen. The internal property is set to a default value in all other cases e.g. when YetAnotherMethod is called from any other class than AnotherConcretObject.
When not using interfaces, this is possible because AnotherConcreteObject is in the same assembly as ConcreteObject so it has access to internal properties and methods. Classes in a different assembly can not set this property or call the method because they don't have access to internal properties and methods.
Upvotes: 3
Views: 1445
Reputation: 43254
There are a couple of possible solutions, depending on what exactly you are doing:
1 if SomePublicMethod
is public, but SomeOtherMethod
is internal, then don't put them in the same class and they likely do very different things and so the separation of concerns principle comes in to play.
2 If ConcreteObject
doesn't have state and doesn't cause side effects, or if you aren't going to run tests against it in parallel, ie has unit behaviour, then it may not need mocking, so access it directly.
Upvotes: 1