【问题标题】:Best Way to Unit Test a Website With Multiple User Types with PHPUnit使用 PHPUnit 对具有多种用户类型的网站进行单元测试的最佳方法
【发布时间】:2010-09-08 16:59:10
【问题描述】:

我开始学习如何使用 PHPUnit 来测试我正在开发的网站。我遇到的问题是我定义了五种不同的用户类型,我需要能够使用不同类型测试每个类。我目前有一个用户类,我想将它传递给每个函数,但我不知道如何传递它或测试可能返回为正确与否的不同错误。

编辑:我应该说。我有一个用户类,我想将此类的不同实例传递给每个单元测试。

【问题讨论】:

    标签: unit-testing types phpunit


    【解决方案1】:

    如果您的各种用户类继承自父用户类,那么我建议您对测试用例类使用相同的继承结构。

    考虑以下示例类:

    class User
    {
        public function commonFunctionality()
        {
            return 'Something';
        }
    
        public function modifiedFunctionality()
        {
            return 'One Thing';
        }
    }
    
    class SpecialUser extends User
    {
        public function specialFunctionality()
        {
            return 'Nothing';
        }
    
        public function modifiedFunctionality()
        {
            return 'Another Thing';
        }
    }
    

    您可以对测试用例类执行以下操作:

    class Test_User extends PHPUnit_Framework_TestCase
    {
        public function create()
        {
            return new User();
        }
    
        public function testCommonFunctionality()
        {
            $user = $this->create();
            $this->assertEquals('Something', $user->commonFunctionality);
        }
    
        public function testModifiedFunctionality()
        {
            $user = $this->create();
            $this->assertEquals('One Thing', $user->commonFunctionality);
        }
    }
    
    class Test_SpecialUser extends Test_User
    {
        public function create() {
            return new SpecialUser();
        }
    
        public function testSpecialFunctionality()
        {
            $user = $this->create();
            $this->assertEquals('Nothing', $user->commonFunctionality);
        }
    
        public function testModifiedFunctionality()
        {
            $user = $this->create();
            $this->assertEquals('Another Thing', $user->commonFunctionality);
        }
    }
    

    因为每个测试都依赖于一个您可以覆盖的 create 方法,并且因为测试方法是从父测试类继承的,所以父类的所有测试都将针对子类运行,除非您覆盖它们以更改预期的行为。

    这在我有限的经验中非常有效。

    【讨论】:

      【解决方案2】:

      如果您想测试实际的 UI,您可以尝试使用 Selenium (www.openqa.org) 之类的工具。它可以让你用 PHP(我假设它可以与 phpUnit 一起使用)编写代码来驱动浏览器..

      另一种方法是使用一个通用方法,每个测试都可以为您的不同用户类型调用该方法。即,类似“ValidatePage”之类的东西,然后您可以从 TestAdminUser 或 TestRegularUser 调用它,并让该方法对您所期望的内容执行相同的基本验证..

      【讨论】:

        【解决方案3】:

        只要确保您没有在此处遇到反模式。也许你在构造函数中做了太多的工作?或者也许这些实际上应该是不同的类?测试通常会为您提供有关代码设计的线索。聆听它们。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-15
          • 2011-02-24
          • 2010-09-25
          • 2012-03-26
          • 2010-09-06
          相关资源
          最近更新 更多