我正在尝试重构项目中的一些类,使它们可以使用接口(interface)和依赖注入(inject)进行测试。但我遇到以下问题:
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;
}
}
到目前为止一切都很好,非常标准的代码。 AnotherConcreteObject 需要调用 SomeOtherMethod,但我不希望其他类(例如在不同的程序集中)能够调用 SomeOtherMethod。所以外部 SomePublicMethod 应该是可见的,但 SomeOtherMethod 不应该是。只有 AnotherConcreteObject 的实例才能调用 SomeOtherMethod。 SomeOtherMethod 将例如设置一个内部属性,稍后 YetAnotherMethod 使用它来确定应该发生什么。在所有其他情况下,内部属性设置为默认值,例如当从 AnotherConcretObject 以外的任何其他类调用 YetAnotherMethod 时。
当不使用接口(interface)时,这是可能的,因为 AnotherConcreteObject 与 ConcreteObject 在同一个程序集中,因此它可以访问内部属性和方法。不同程序集中的类无法设置此属性或调用该方法,因为它们无权访问内部属性和方法。
最佳答案
有几种可能的解决方案,具体取决于您在做什么:
1 如果SomePublicMethod
是公共(public)的,但是SomeOtherMethod
是内部的,那么不要把它们放在同一个类中,它们可能做的事情非常不同,所以分离关注原则开始发挥作用。
2 如果 ConcreteObject
没有状态并且不会引起副作用,或者如果您不打算并行运行针对它的测试,即具有单元行为,那么它可能不需要模拟,所以直接访问它。
关于c# 依赖注入(inject)与接口(interface)和隐藏内部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20160660/