Unit test to verify that a base class method is called

前端 未结 3 1113
有刺的猬
有刺的猬 2020-12-11 20:29

I have a base class:

public abstract class MyBaseClass
{
    protected virtual void Method1()
    {    
    }
} 

and a derived class:

3条回答
  •  遥遥无期
    2020-12-11 21:16

    What you're describing is not a test of your code, but a test of the behavior of the language. That's fine, because it's a good way to ensure that the language behaves the way we think it does. I used to write lots of little console apps when I was learning. I wish I'd known about unit testing then because it's a better way to go about it.

    But once you've tested it and confirmed that the language behaves the way you expect, I wouldn't keep writing tests for that. You can just test the behavior of your code.

    Here's a real simple example:

    public class TheBaseClass
    {
        public readonly List Output = new List();
    
        public virtual void WriteToOutput()
        {
            Output.Add("TheBaseClass");
        }
    }
    
    public class TheDerivedClass : TheBaseClass
    {
        public override void WriteToOutput()
        {
            Output.Add("TheDerivedClass");
            base.WriteToOutput();
        }
    }
    

    Unit test

        [TestMethod]
        public void EnsureDerivedClassCallsBaseClass()
        {
            var testSubject = new TheDerivedClass();
            testSubject.WriteToOutput();
            Assert.IsTrue(testSubject.Output.Contains("TheBaseClass"));
        }
    

提交回复
热议问题