使用PHPUnit对具有多个用户类型的网站进行单元测试的最佳方法 [英] Best Way to Unit Test a Website With Multiple User Types with PHPUnit

查看:56
本文介绍了使用PHPUnit对具有多个用户类型的网站进行单元测试的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm starting to learn how to use PHPUnit to test the website I'm working on. The problem I'm running into is that I have five different user types defined and I need to be able to test every class with the different types. I currently have a user class and I would like to pass this to each function but I can't figure out how to pass this or test the different errors that could come back as being correct or not.

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

I should have said. I have a user class and I want to pass a different instance of this class to each unit test.

推荐答案

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

If your various user classes inherit from a parent user class, then I recommend you use the same inheritance structure for your test case classes.

请考虑以下示例类:

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';
    }
}

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

You could do the following with your test case classes:

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方法,并且由于该测试方法是从父测试类继承的,所以除非您重写它们以更改子类,否则所有针对父类的测试都将针对子类运行.预期的行为.

Because each test depends on a create method which you can override, and because the test methods are inherited from the parent test class, all tests for the parent class will be run against the child class, unless you override them to change the expected behavior.

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

This has worked great in my limited experience.

这篇关于使用PHPUnit对具有多个用户类型的网站进行单元测试的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆