Symfony 3에서 Doctrine과 함께 데이터베이스에 "마지막으로 업데이트 한"컬럼이 있습니다. 변경 사항이 테이블에 저장 될 때마다 로그인 된 사용자의 사용자 이름으로 자동 설정됩니다. .Symfony 유닛 테스트 중에 사용자 이름을 얻을 수 없습니다.
내가 진짜 시스템을 사용할 때 작동하는이 작업을 수행하기 위해 EventSubscriber
를 사용하여,하지만 난 그게 생각하는 단위 테스트를 실행할 때 로그인 한 사용자가없는입니다.
을 내가 how to implement authentication for unit tests의 지침에 따라입니다 기본 인증을 사용하거나 토큰을 설정하는 두 가지 방법을 조언합니다. 이 두 방법 모두 사용자가 인증 된 것처럼 테스트를 실행할 수 있지만 둘 다 로그인 한 사용자의 사용자 이름을 검색 할 수 없기 때문에 "마지막 업데이트 기준"열이 올바르게 설정되어 있는지 테스트 할 수 없습니다.
내가 뭘 잘못하고 있니? EventSubscriber
에 로그인 한 사용자의 사용자 이름을 검색해야하는 다른 방법이 있습니까?
이 실제 요청을 작동 내 EventSubscriber
구현하지만, 테스트가 실행중인 널 토큰을 반환
class BaseEntitySubscriber implements EventSubscriber {
public function getSubscribedEvents() {
return array('prePersist');
}
public function prePersist(LifecycleEventArgs $args) {
$em = $args->getEntityManager();
$token = $this->ts->getToken(); // returns null during tests
$username = $token ? $token->getUsername() : null;
if ($username === null) throw new \Exception("User is not logged in!");
$entity = $args->getEntity();
$entity->setLastUpdateBy($username);
}
}
# services.yml
AppBundle\EventListener\BaseEntitySubscriber:
tags:
- { name: doctrine.event_subscriber, connection: default }
arguments: [ "@security.token_storage" ]
편집 : 테스트 코드는 다음과 같습니다 @dbrumann : (약)
를public function testEditLookup()
{
$idLookup = $this->getFixtureId('lookup.example');
// Get the existing one first so we know if it changes later.
$crawler = $this->client->request('GET', "/lookup/$idLookup");
$lookup = $this->decodeSymfonyJSON($this->client->getResponse());
$this->assertEquals('Old title', $lookup['title']);
$this->assertEquals('system', $lookup['last_update_by']);
$this->assertEquals('Example', $lookup['detail']);
// Make the change.
$crawler = $this->client->request('PATCH',
"/lookup/$idLookup",
array('title' => 'New title')
);
$this->checkSymfonyError($this->client->getResponse());
// Retrieve it again to confirm it is now different.
$crawler = $this->client->request('GET', "/lookup/$idLookup");
$lookup = $this->decodeSymfonyJSON($this->client->getResponse());
$this->assertEquals('New title', $lookup['title']);
$this->assertEquals('testuser', $lookup['last_update_by']);
// Make sure this hasn't changed.
$this->assertEquals('Example', $lookup['detail']);
}
테스트는 어떻게 생겼습니까? – dbrumann