假设我有以下课程:
public class TestBase { public bool runMethod1 { get; set; } public void BaseMethod() { if (runMethod1) ChildMethod1(); else ChildMethod2(); } protected abstract void ChildMethod1(); protected abstract void ChildMethod2(); }
我也有课
public class ChildTest : TestBase { protected override void ChildMethod1() { //do something } protected override void ChildMethod2() { //do something completely different } }
我正在使用Moq,我想编写一个测试来验证当我调用BaseMethod()并且runMethod1为true时调用ChildMethod1().是否可以使用Moq创建TestBase的实现,调用BaseMethod()并验证是否在Moq实现上调用了ChildMethod?
[Test] public BaseMethod_should_call_correct_child_method() { TestBase testBase; //todo: get a mock of TestBase into testBase variable testBase.runMethod1 = true; testBase.BaseMethod(); //todo: verify that ChildMethod1() was called }
kzu.. 5
您还可以将期望/设置设置为可验证,并且不需要严格模拟:
//expect that ChildMethod1() will be called once. (it's protected) testBaseMock.Protected().Expect("ChildMethod1") .AtMostOnce() .Verifiable(); ... //make sure the method was called testBase.Verify();
编辑 此语法在当前版本的Moq中不起作用.请参阅此问题,了解如何执行此操作至少4.0.10827
您还可以将期望/设置设置为可验证,并且不需要严格模拟:
//expect that ChildMethod1() will be called once. (it's protected) testBaseMock.Protected().Expect("ChildMethod1") .AtMostOnce() .Verifiable(); ... //make sure the method was called testBase.Verify();
编辑 此语法在当前版本的Moq中不起作用.请参阅此问题,了解如何执行此操作至少4.0.10827