使用Moq调用验证受保护的抽象方法

Lan*_*her 3 c# testing unit-testing moq

假设我有以下课程:

public class TestBase
{
  public bool runMethod1 { get; set; }

  public void BaseMethod() 
  {
    if (runMethod1)
      ChildMethod1();
    else 
      ChildMethod2();
  }

  protected abstract void ChildMethod1();
  protected abstract void ChildMethod2();
}
Run Code Online (Sandbox Code Playgroud)

我也有课

public class ChildTest : TestBase
{
  protected override void ChildMethod1()
  {
    //do something
  } 

  protected override void ChildMethod2()
  {
    //do something completely different
  }

}
Run Code Online (Sandbox Code Playgroud)

我正在使用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

}
Run Code Online (Sandbox Code Playgroud)

kzu*_*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();
Run Code Online (Sandbox Code Playgroud)

编辑 此语法在当前版本的Moq中不起作用.请参阅此问题,了解如何执行此操作至少4.0.10827