可以用 behat 测试存储库吗?

Is it ok to test repository with behat?

我想测试添加用户的功能。

我写了以下场景:

Feature: Add users
  In order to have users
  As an admin
  I need to be able to add users to database

  Rules:
  - User has a name

  Scenario: Adding user with name 'Jonas'
    Given There is no user 'Jonas'
    When I add the user with name 'Jonas'
    Then I should have user 'Jonas' in a system

以及以下测试:

<?php

use AppBundle\Repository\UserRepository;
use Behat\Behat\Tester\Exception\PendingException;
use Behat\Behat\Context\Context;
use Behat\Behat\Context\SnippetAcceptingContext;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;
use AppBundle\Entity\User;
use Symfony\Component\Config\Definition\Exception\Exception;

/**
 * Defines application features from the specific context.
 */
class FeatureContext implements Context, SnippetAcceptingContext
{
    private $userRepository;

    /**
     * Initializes context.
     *
     * Every scenario gets its own context instance.
     * You can also pass arbitrary arguments to the
     * context constructor through behat.yml.
     */
    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    /**
     * @Given There is no user :arg1
     */
    public function thereIsNoUser($arg1)
    {
        $user = $this->userRepository->findOneBy(['name' => $arg1]);
        if ($user) {
            $this->userRepository->delete($user);
        }
    }

    /**
     * @When I add the user with name :arg1
     */
    public function iAddTheUserWithName($arg1)
    {
        $user = new User($arg1);
        $this->userRepository->add($user);
    }

    /**
     * @Then I should have user :arg1 in a system
     */
    public function iShouldHaveUserInASystem($arg1)
    {
        $user = $this->userRepository->findOneBy(['name' => $arg1]);

        if (!$user) {
            throw new Exception('User was not added');
        }

        $this->userRepository->delete($user);
    }
}

我不确定我是否以 correct/quality 方式来做,所以优秀的程序员会认为它很好。 我是否按我想要的方式进行测试? 还是我应该从头到尾进行测试 - 调用控制器方法并检查响应?我相信调用控制器方法会测试更多,因为我们也可以破坏控制器中的某些东西,例如返回的状态代码,或 json 格式。

但在 behat 文档中,我看到了一个测试示例 class - 篮子和货架:

http://docs.behat.org/en/v3.0/quick_intro_pt1.html

所以我想 - 我也可以测试特定的 class - 存储库。

要调用控制器方法,我还需要使用一些伪造的浏览器 - http://mink.behat.org/en/latest

这可能更有效。

是的,你可以测试你想要的,但是最好用 scenarios/flows 定义一些特征。

如果您想要并需要进行端到端测试,那么就进行测试,否则测试您需要测试的内容。

关于控制器方法调用,你应该做合乎逻辑的事情并为你的套件带来价值,你需要记住的是处理异常并抛出对你有意义的适当异常。

尝试快速制定计划,您还可以与团队中可以为自动化方法添加一些有价值的输入的人员讨论您需要涵盖的内容。

其他要记住的事情:看看 Mink 驱动程序和页面对象。