问题描述
考虑下面的类
public class Entity {
public void Foo() { ... }
internal void Bar() { ... }
}
如你所见它有一个公共
方法和内部
方法。现在,我想创建一个接口,这将使我嘲笑这个类在测试中(无论是在本次大会,并在其他)。我重写我的代码如下:
As you see it has a public
method and an internal
method. Now, I would like to create an interface which will allow me to mock this class in tests (both in this assembly and in others). I rewrite my code as following:
public interface IEntity {
void Foo();
}
internal class Entity : IEntity {
public void Foo() { ... }
public void Bar() { ... }
}
不过,这造成的另一个问题。当另一种方法在同一装配使用类我不能叫酒吧
了:
However, this creates another issue. When using the class in another method in the same assembly I can't call Bar
anymore:
public class OtherClass {
public void SomeMethod(IEntity entity) {
entity.Bar(); // error!
}
}
重写代码是这样的:
Rewriting the code like this:
public class OtherClass {
public void SomeMethod(IEntity entity) {
(entity as Entity).Bar(); // error in test!
}
}
将触发触发的someMethod 。我如何重写我的代码,这样我仍然可以使用内部
方法在同一集会,但公共成员只有暴露在其他组件?
will trigger an error in the unit test that triggers SomeMethod
. How do I rewrite my code so that I can still use internal
methods in the same assembly and yet only expose public members to other assemblies?
更新:类 OtherClass
是需要在实体的内部类,它不直接暴露于用户。但是,此类本身暴露给用户,让他们间接有机会获得
实体
的内部。这需要为的someMethod
将进行必要的检查,以确保用户不会搞砸的内部状态实体
。对象
Update: Class OtherClass
is a utility class that needs to operate on internals of the Entity
class, which are not exposed to the users directly. However, this class itself is exposed to users, so they indirectly have access to internals of the Entity
. This is desired as SomeMethod
will perform necessary checks to ensure that users won't screw up the internal state of an Entity
object.
推荐答案
编辑:
扩展你的 IEntity
与内部 ITestEntity
接口测试界面:
Extend your IEntity
interface with an internal ITestEntity
interface for testing:
public interface IEntity
{
//Implementation
}
internal interface ITestEntity : IEntity
{
void TestMethod();
}
class Entity: ITestEntity
{
//
}
这篇关于如何创建保持一些方法内部在C#中测试的接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!