2016-06-12 58 views
0

我有一個應用程序在Symfony 3與Web應用程序和REST API。Symfony功能測試in_memory用戶getId

我寫使用的Symfony \包\ FrameworkBundle \測試\功能測試WebTestCase

$this->client = static::createClient(array(), array(
     'PHP_AUTH_USER' => 'test', 
     'PHP_AUTH_PW' => 'test', 
    )); 

public function testIndex() 
{ 
    $this->client->request(
     'GET', 
     '/titles' 
    ); 
    $response = $this->client->getResponse(); 
    $this->assertEquals(200, $response->getStatusCode()); 
} 

我對API和form_login爲webapp的OAuth認證。 對於我的測試中,我使用http_basic,這裏是我的config_test.yml:

security: 
encoders: 
     Symfony\Component\Security\Core\User\User: plaintext 
firewalls: 
    api: 
     http_basic: ~ 
    main: 
     http_basic: ~ 
providers: 
    in_memory: 
     memory: 
      users: 
       test: { password: test, roles: [ 'ROLE_USER' ] } 

在我的控制,我得到用戶是這樣的:

$this->getUser()->getId() 

當我啓動PHPUnit的,我得到

Error: Call to undefined method Symfony\Component\Security\Core\User\User::getId() 

它沒有使用我的用戶實體進行測試,我該怎麼辦?

回答

0

它不使用我的用戶實體測試

這是因爲在內存供應商uses the built in UserInterface implementation。 InMemoryUserProvider永遠不會使用你的實體 - 它基於一個完全不同的系統而不是一個教條用戶提供者。

你有幾種解決方法。

  1. 使用數據庫和原則一樣。這絕對是你應該做的:端到端測試應該真正結束並有用。而且,如果你在測試中不使用數據庫和原則,那麼與用戶實體相關的東西(通過外鍵)將會失敗。
  2. 創建一個custom user provider,它模仿InMemoryUserProvider的行爲,但使用您的自定義實體類。