我正在用PHPUnit做一些测试,但是我有一些问题,尤其是在测试Controller时。
我只想通过调用路由来测试Controller的路由,并检查响应是否为HTTP-Status200。但是控制台仍然存在smae错误。
这也是他遇到的401错误。
我的PHPUnit-Test看起来像这样:
命名空间App \ Tests \ Controller;
使用Symfony \ Bundle \ FrameworkBundle \ Test \ WebTestCase;
PersonControllerTest类扩展了WebTestCase { 私人$ client;
data
}
我已经尝试过使用setUp方法中的身份验证进行操作->无效。
你有什么线索吗?
感谢所有答案或/和评论
答案 0 :(得分:0)
基本身份验证:
/**
* @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());
}
答案 1 :(得分:0)
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());
}
}
解决方案仅是登录功能。 $ testUser必须位于您的Active Directory或网络中。其余参数无关紧要。
我的防火墙阻止了它,因此我无法以正常方式进行操作。
如果您这样做,则必须在安装PHPUnit时创建的secourity.yaml中添加一些东西。