hen*_*nit 3 session phpunit header silex
我正在尝试为我的Silex应用程序创建一个单元测试.单元测试类看起来像这样:
class PageTest extends WebTestCase {
public function createApplication() {
$app = require __DIR__ . '/../../app/app.php';
$app['debug'] = true;
$app['session.storage'] = $app->share(function() {
return new MockArraySessionStorage();
});
$app['session.test'] = true;
unset($app['exception_handler']);
return $app;
}
public function testIndex() {
$client = $this->createClient();
$client->request('GET', '/');
$this->assertTrue($client->getResponse()->isOk());
}
}
Run Code Online (Sandbox Code Playgroud)
和它试图请求的silex路径看起来像这样:
$app->get('/', function() use($app) {
$user = $app['session']->get('loginUser');
return $app['twig']->render('views/index.twig', array(
'user' => $user,
));
});
Run Code Online (Sandbox Code Playgroud)
这会导致RuntimeException:由于已经发送了标头,因此无法启动会话.在\ Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage.php:142中有一个回溯,其中包含来自$ app ['session'] - > get的路线中的行.
看起来在NativeSessionStorage中会话开始尝试之前发生的输出实际上是PHPUnit输出信息,因为这是我在错误消息之前得到的唯一输出:
PHPUnit 3.7.8 by Sebastian Bergmann.
Configuration read from (PATH)\phpunit.xml
E.......
Run Code Online (Sandbox Code Playgroud)
我有点困惑,因为phpunit的这个错误输出发生在执行实际测试方法之前的输出中.我没有运行任何其他测试方法,因此它必须来自此错误.
我怎么能让PHPUnit在使用会话变量的silex路由上工作?
好的,我遇到了同样的问题,经过一个小时的浏览网络后,我设法通过了测试.
在Silex 2.0-dev上,$app['session.test'] = true从WebTestCase类中调用根本不起作用,它需要在引导程序中发生.
实现它的方法很多,其中有两种:
1/phpunit.xml.dist
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="./app.php"
>
<php>
<env name="TEST" value="true" /> //-> This is the trick
</php>
<testsuites>
<testsuite name="Your app Test Suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>
</phpunit>
Run Code Online (Sandbox Code Playgroud)
然后在bootstrap中
$app = new \Silex\Application();
...
$app->register(new \Silex\Provider\SessionServiceProvider(), [
'session.test' => false !== getenv('TEST')
]);
...
return $app;
Run Code Online (Sandbox Code Playgroud)
2 /通过扩展Silex\Application,您可以将环境传递给构造函数
namespace Your\Namespace;
class YourApp extends \Silex\Application
{
public function __construct($env, array $params = array())
{
$this['env'] = $env;
parent::__construct($params);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的引导程序中
$env = // Your logic ...
$app = new \Your\Namespace\YourApp($env);
...
$app->register(new \Silex\Provider\SessionServiceProvider(), [
'session.test' => 'test' === $app['env'],
]);
...
return $app;
Run Code Online (Sandbox Code Playgroud)
希望有所帮助,欢呼!
| 归档时间: |
|
| 查看次数: |
1373 次 |
| 最近记录: |