Sam*_*der 2 .net c# rhino-mocks mocking partial-mocks
我有一个用户控件,它在我想测试的ValidateChildren方法中做了一些验证.我创建了一个用户控件的部分模拟,但是虽然我没有对ValidateChildren方法设置任何期望,但我只是调用它,它只是被跳过而且方法中的代码永远不会执行.为了尝试了解发生了什么,我创建了一个简单的测试,如下所示:
public class Foo
{
public virtual bool Method1()
{
throw new NotImplementedException();
}
public virtual bool Method2()
{
return Method1();
}
}
Run Code Online (Sandbox Code Playgroud)
并用它来测试它:
[Test]
public void TestFooMethods ()
{
MockRepository m = new MockRepository();
Foo foo = m.PartialMock<Foo>();
RhinoMocksExtensions.Expect<Foo,bool>(
foo,
delegate (Foo obj)
{
return obj.Method1();
}
).Return(true);
Assert.IsTrue (foo.Method2());
}
Run Code Online (Sandbox Code Playgroud)
现在我希望foo.Method1被嘲笑和foo.Method2不是.但是这总是返回false,如果我尝试在调试器中逐步执行foo.Method2(),我就不能介入它了.
有什么想法吗?
如果模拟一个对象,它将覆盖所有抽象/虚拟方法,而不管mock的类型如何.你可以做的是对你的方法做一个期望并告诉它执行它覆盖的原始方法,使用:
CallOriginalMethod(OriginalCallOptions.CreateExpectation);
Run Code Online (Sandbox Code Playgroud)
你没有按照设计的方式使用Rhino Mocks,这也可能会给你带来麻烦.我已经按照应该使用C#3.0和lambda和扩展方法编写的方式重新编写了测试:
[TestMethod]
public void TestFooMethods()
{
//Generate a new Mock to test against
Foo foo = MockRepository.GenerateMock<Foo>();
//Expect a call to Method1 on object foo and return true
foo.Expect(f => f.Method1()).Return(true);
//Expect a call to Method2 on object foo and call the original method
foo.Expect(f => f.Method2()).CallOriginalMethod(OriginalCallOptions.CreateExpectation);
Assert.IsTrue(foo.Method2());
//Verify all our expectations on foo
foo.VerifyAllExpectations();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1547 次 |
| 最近记录: |