考虑:
class MyClass{ //Implementation public void Foo() {}}class SomethingYouWantToTest{ public bool MyMethod(MyClass c) { //Code you want to test c.Foo(); }}因为
MyMethod只接受一个
MyClass,所以如果您想
MyClass用一个模拟对象替换它以便进行单元测试,则不能。更好的方法是使用接口:
interface IMyClass{ void Foo();}class MyClass : IMyClass{ //Implementation public void Foo() {}}class SomethingYouWantToTest{ public bool MyMethod(IMyClass c) { //Code you want to test c.Foo(); }}现在您可以进行测试
MyMethod,因为它仅使用一个接口,而不使用特定的具体实现。然后,您可以实现该接口以创建您想要用于测试目的的任何模拟或伪造。甚至还有像Rhino
Mocks’之类的库
Rhino.Mocks.MockRepository.StrictMock<T>(),它们都可以采用任何接口并为您动态构建一个模拟对象。



