Installation PHPUnit中的setup()与Codeception中之前的_有什么区别

Installation PHPUnit中的setup()与Codeception中之前的_有什么区别,installation,phpunit,codeception,teardown,Installation,Phpunit,Codeception,Teardown,我正在学习Codeception,我想知道什么时候应该使用setUp()或tearDown(),什么时候应该使用_before()或_after()。 我看不出有什么不同。这两种方法都是在我的测试文件中的单个测试之前还是之后运行的? 谢谢,正如Gabriel Hemming所提到的,setUp()和tearDown()是PHPUnit在每次测试运行前设置环境,并在每次测试运行后拆除环境的方法_before()和_after()是codeception的实现方式 要回答您的问题,关于为什么code

我正在学习Codeception,我想知道什么时候应该使用setUp()或tearDown(),什么时候应该使用_before()或_after()。 我看不出有什么不同。这两种方法都是在我的测试文件中的单个测试之前还是之后运行的?
谢谢,

正如Gabriel Hemming所提到的,setUp()和tearDown()是PHPUnit在每次测试运行前设置环境,并在每次测试运行后拆除环境的方法_before()和_after()是codeception的实现方式

要回答您的问题,关于为什么codeception有不同的方法集,请让我参考codeception的文档:

如您所见,与PHPUnit不同,setUp和tearDown方法被替换为它们的别名:_before,_after

实际的设置和拆卸由父类\Codeception\TestCase\Test实现,并将UnitTester类设置为将Cept文件中的所有酷操作作为单元测试的一部分运行

文档所指的酷动作是现在可以在单元测试中使用的任何模块或帮助器类

下面是如何在单元测试中使用模块的一个很好的示例:

让我们举一个在单元测试中设置夹具数据的示例:

<?php


class UserRepositoryTest extends \Codeception\Test\Unit
{
    /**
     * @var \UnitTester
     */
    protected $tester;

    protected function _before()
    {
        // Note that codeception will delete the record after the test.
        $this->tester->haveInDatabase('users', array('name' => 'miles', 'email' => 'miles@davis.com'));
    }

    protected function _after()
    {

    }

    // tests
    public function testUserAlreadyExists()
    {

        $userRepository = new UserRepository(
            new PDO(
                'mysql:host=localhost;dbname=test;port=3306;charset=utf8',
                'testuser',
                'password'
            )
        );

        $user = new User();
        $user->name = 'another name';
        $user->email = 'miles@davis.com';

        $this->expectException(UserAlreadyExistsException::class);

        $user->save();

    }
}

class User
{
    public $name;
    public $email;

}

class UserRepository
{
    public function __construct(PDO $database)
    {
        $this->db = $database;
    }

    public function save(User $user)
    {
        try {
            $this->db->prepare('INSERT INTO `users` (`name`, `email`) VALUES (:name, :email)')
                ->execute(['name' => $user->name, 'email' => $user->email]);
        } catch (PDOException $e) {
            if ($e->getCode() == 1062) {
                throw new UserAlreadyExistsException();
            } else {
                throw $e;
            }
        }

    }
}

有什么意义?这些方法有完全相同的行为,只是它们来自不同的库。但是为什么Codeception集成了这些方法呢?我想这一定是有原因的。单元测试也是这样吗?如果我继续进行功能测试和验收测试,我确实需要这种方法吗?哦,这是另一个问题,不是区别,而是目的/原因。看看上面的链接。直到现在,还不需要一个完整的答案:谢谢你的回答。但是现在我仍然不知道在使用codeception创建单元测试时使用方法_before()还是使用方法setup()是有利的。“但是为什么Codeception集成了这个方法”这句话并不是方法设置()的目的。在()之前使用该方法。