我是使用 Mocking 框架来模拟对象以进行单元测试的新手。我目前正在使用 Rhino Mocks,我认为它会有一种方法来做我找不到的事情。这是一个 LinqPad 程序(只需将其复制并粘贴到 C# 程序查询中,它就可以工作),它显示了我正在尝试做的事情:
public interface MyTest{
int A(int i);
string B(int i);
}
/// This is an actual class that is a black box to me.
public class ActualClass : MyTest {
public int A(int i){
// Does some work
return ++i;
}
public string B(int i){
return A(i).ToString();
}
}
/// I'd like to create a mocked class that uses an instance of the actual class
/// to provide all of the implementations for the interface except for a single method
/// where I can check the parameter values, and provide my own return value,
/// or just call the actual class
public class MockedClass : MyTest {
private ActualClass _actual;
public MockedClass(ActualClass actual){
_actual = actual;
}
public int A(int i){
if(i == 1){
return 10;
}else{
return _actual.A(i);
}
}
public string B(int i){
return _actual.B(i);
}
}
void Main()
{
var mock = new MockedClass(new ActualClass());
mock.A(0).Dump();
mock.A(1).Dump();
mock.A(2).Dump();
mock.B(0).Dump();
mock.B(1).Dump();
mock.B(2).Dump();
}
结果:
1
10
3
1
2
3
我该怎么做才能模拟这个进行单元测试。我需要某种依赖注入器吗?