代码之家  ›  专栏  ›  技术社区  ›  ryeguy

当您使用私有方法的知识来选择测试用例时,是否显式地对私有方法进行单元测试?

  •  3
  • ryeguy  · 技术社区  · 14 年前

    似乎测试界的普遍共识是 测试私有方法。相反,你应该 test private methods by testing the public methods that invoke them . 但是,我觉得有些事情不对劲。让我们以这个方法为例:

    /**
     * Returns the base name of the output generator class. If the class is named
     * Reno_OutputGenerator_HTML, this would return "HTML".
     *
     * @return string
     */
    protected function getName()
    {
        $class = get_class($this);
        $matches = array();
    
        if (preg_match('/^Reno_OutputGenerator_(.+)$', $class, $matches))
        {
            return $matches[1];
        }
        else
        {
            throw new Reno_OutputGenerator_Exception('Class name must follow the format of Reno_OutputGenerator_<name>.');
        }
    }
    

    这个特殊的函数在我们班的几个地方使用。我想测试 if 这个函数中的语句,这意味着对于每个公共函数,我必须测试这两种情况以及公共方法本身所做的其他操作。

    这就是我觉得奇怪的地方。如果我在测试 getName() 在满足特定条件时引发异常,这意味着我必须知道私有方法的实现细节。如果我必须知道这一点,那么为什么我不应该扩展类,公开方法,然后用这种方式测试它呢?

    (顺便说一句:如果您想知道为什么会存在这样一个奇怪的方法,可以使用这个方法自动确定这个类的模板文件存储在哪个目录中)。

    2 回复  |  直到 14 年前
        1
  •  2
  •   mlschechter    14 年前
        2
  •  0
  •   slamidtfyn    14 年前

    namespace TheProject
    {
        public class ClassUnderTest
        {
            protected string GetName()
            {
                return "The name";
            }
        }
    }
    
    namespace TestProject
    {
        [TestClass]
        public class TheTest:TheProject.ClassUnderTest
        {
            [TestMethod]
            public void TestGetName()
            {
                string expected = "The name";
                string actual = GetName();
                Assert.AreEqual(expected, actual);
            }
        }
    }