您应该使用它的接口。
public interface IMemberInstance
{
int xyz {get;}
}
public class MemberInstance : IMemberInstance
{
... // the real class's implementation + code here
}
public class MockMemberInstance : IMemberInstance
{
// the test class can return a test value
int xyz(int a) { return 10; }
}
然后在您的班级中进行测试(例如 MyClass)
private IMemberInstance memberInstance;
public MyClass(IMemberInstance memberInstance)
{
this.memberInstance = memberInstance;
}
int sum(int a, int b)
{
int x = memberInstance.xyz(a); // memberInstance is an object of another class
.....
.....
}
这样做,以便您可以将 IMemberInstance 传递给要测试的类。这样你就可以用一个测试类来伪造它(模拟实现)