使用 PHPUnit 测试控制器,但会抛出 401 错误

Testing Controller with PHPUnit, but it throws a 401 Error

我正在用 PHPUnit 做一些测试,但我遇到了一些问题,尤其是在测试 Controller 时。

我想通过调用路由来测试控制器的路由,并检查响应是否为 HTTP-Status 200。但是控制台总是出现 smae 错误。

它说了一些关于丢失的令牌。我不知道这是什么类型的令牌。

这也是他收到的 401 错误。

我的 PHPUnit-Test 看起来像这样:

命名空间App\Tests\Controller;

使用Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class PersonControllerTest 扩展 WebTestCase { 私人 $client;

protected function setUp()
{
    $this->client = static::createClient([], [
        'PHP_AUTH_USER' => 'user',
        'PHP_AUTH_PW'   => 'pass',
    ]);
}


public function testCreate()
{

    $this->client->request('GET','/create');

    $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
}

public function testIndex()
{

    $this->client->request('GET','/');

    $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
}

}

我已经尝试使用设置方法中的身份验证 -> 没有用。

你有什么线索吗?

感谢所有回答or/and评论

基本授权:

   /**
     * @dataProvider urlProvider
     */
    public function testPageIsSuccessful($url)
    {
        $client = self::createClient([], [
            'PHP_AUTH_USER' => getenv('PHP_AUTH_USER'),
            'PHP_AUTH_PW' => getenv('PHP_AUTH_PW')
        ]);
        $client->request('GET', $url);
        $this->assertTrue($client->getResponse()->isSuccessful());
    }

API 键

    /**
     * @dataProvider urlApiProvider
     */
    public function testAPIWorks($url)
    {
        $accessToken = $this->getAccessToken();
        $tokenQuery = http_build_query(['access_token' => $accessToken]);
        $url .= '?' . $tokenQuery;
        $client = self::createClient([]);
        $client->request('GET', $url, [], [], ['HTTP_ACCEPT' => 'application/json']);

        $this->assertTrue($client->getResponse()->isSuccessful());
    }
protected function setUp()
{
    $this->client = static::createClient();

    $this->logIn();
}

private function logIn()
{
    $session = $this->client->getContainer()->get('session');

    $firewallName = 'test';
    // if you don't define multiple connected firewalls, the context defaults to the firewall name
    // See https://symfony.com/doc/current/reference/configuration/security.html#firewall-context
    $firewallContext = 'test';

    // you may need to use a different token class depending on your application.
    // for example, when using Guard authentication you must instantiate PostAuthenticationGuardToken
    $testUser = new WebserviceUser('Test@Test.com', ['ROLE_ADMIN'],
        array("employeeid" => array(420),
        "mail" => array("testing@test.com")), false);
    $token = new UsernamePasswordToken($testUser, null, $firewallName, ['ROLE_ADMIN']);
    //var_dump($token);
    $session->set('_security_' . $firewallContext, serialize($token));
    $session->save();

    $cookie = new Cookie($session->getName(), $session->getId());
    $this->client->getCookieJar()->set($cookie);
}


public function testCreate()
{

    $crawler = $this->client->request('GET', '/create');
    $this->assertEquals(200, $this->client->getResponse()->getStatusCode());

    $form = $crawler->filter('form')->form([
        'person[name]' => 'Chruit',
        'person[birthdate][month]' => 2,
        'person[birthdate][day]' => 15,
        'person[birthdate][year]' => 2014,
    ]);

    $this->client->submit($form);
}

public function testIndex()
{

    $this->client->request('GET', '/');

    $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
}

}

解决方案就是 logIn-Function。 $testUser 需要在您的 Active Directory 或您的网络中。其余参数无关紧要。

我的防火墙阻止了它,所以我无法以正常方式进行。

如果您这样做,则必须向从安装 PHPUnit 创建的 secourity.yaml 添加一些内容。