如何覆盖基本抽象类的行为?

时间:2016-12-05 19:17:36

标签: c# .net unit-testing nunit moq

如何在测试派生类时覆盖基类行为?

public abstract BaseController
{
    public virtual bool DoStuff(){};
}

public class UsageController : BaseController
{
    public string MethodToTest()
    {
       if (base.DoStuff())
          {return "yes";}
       return "no";
    }
}

我想设置 DoStuff()的返回值,这可能吗?

[Test]
public void Returns_Yes_When_True()
{
     var sut = new UsageController();
     //how would I setup the behavior of DoStuff?
     Assert.That(sut.MethodToTest()=="yes");
}

1 个答案:

答案 0 :(得分:3)

  

在测试派生类时,如何覆盖基类行为?

实际上覆盖它。但UsageController未被密封。

public class TestController : UsageController {
    public override bool DoStuff(){ return true; };
}

从派生类继承并在测试中使用存根

[Test]
public void Returns_Yes_When_True() {
    //Arrange
    var expected = "yes";
    var sut = new TestController();
    //Act
    var actual = sut.MethodToTest();
    //Assert
    Assert.That(expected == actual);
}

更新:

当您删除base并调用实例方法

时,它会通过
public class UsageController : BaseController {
    public string MethodToTest() {
       if (DoStuff())
          {return "yes";}
       return "no";
    }
}

这是有道理的,因为如果我没记错,指南建议在覆盖范围内调用base

base (C# Reference)