c# - 单元测试调用另一个类的其他方法的方法

标签 c# .net visual-studio-2010

请看下面的代码

int sum(int a, int b)
{
    int x = memberInstance.xyz(a); // memberInstance is an object of another class
    .....
    .....
}

比如说,众所周知,xyz 方法返回 1-10 之间的数字。 现在,我想为 sum 方法开发单元测试方法,我想用任意返回值 [1-10 之间的任何值] 替换方法调用 memberInstance.xyz(a) 。请让我知道我怎样才能做到这一点?如果可能,请提供示例代码。

最佳答案

你应该使用它的接口(interface)。

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 传递给要测试的类。这样你就可以用一个测试类来伪造它(模拟实现)

关于c# - 单元测试调用另一个类的其他方法的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15151772/

相关文章:

c# - 打开表单时如何设置对TextBox的关注?

c# - 如何以不可变的方式实现缓存?

c# - 交互服务与交互请求对象

c# - .NET 中如何实现 "Event"对象?

c++ - 如何阻止函数在 MS VS C++ 中导出?

c# - 方法参数是否引用

c# - 将 net.tcp 用于 STS 的问题

.net - 设置驻留在 UserControl 中的 ItemsControl 的 ItemTemplate

c# - 在 Visual Studio 的设计器中,为什么没有任何图像显示在选择资源窗口中?

c++ - 迭代器使用的编译时间验证?