擅长:python、mysql、java
<p><strong>从理论角度来看,您只需要测试可实例化类的公共方法(在标准OOP语言中)。测试内部行为是没有意义的,因为您只需要“该输入的输出”(针对特定方法或整个类)。您应该尽量尊重它,因为它会迫使您对类的<a href="http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)" rel="noreferrer">encapsulation</a>和提供的接口提出一些问题,这些问题可能对您的体系结构起决定性作用。</p>
<p><strong>从实用的角度来看,有时您可能会有一些抽象的helper类,这些类没有实现的具体子类,或者抽象类分解了90%以上的子类,并且如果不插入受保护的方法就很难测试输出。在这种情况下,您可以<a href="http://en.wikipedia.org/wiki/Mock_object" rel="noreferrer">mock</a>一个子类。</p>
<p>在您的简单示例中,我建议您只测试类<code>Tiger</code>(并且只测试公共方法<code>eat</code>)。</p>
<blockquote>
<p>Just a note for people thinking to <a href="http://en.wikipedia.org/wiki/Test-driven_development" rel="noreferrer">TDD</a>. In TDD, you shouldn't have started to code the class <code>Mammal</code> before the class <code>Tiger</code> because <code>Mammal</code> should be the result of a refactoring phase. So, you certainly woudn't have any specific test for <code>Mammal</code>.</p>
</blockquote>