我一直在尝试对修改其他人代码的示例进行单元测试,每次我到达测试运行时都没有错误的程度 - 当我期望它们通过时,我只是遇到相同的失败。网上没有大量文档,我真的不知道还能去哪里。任何人都可以看到我的代码哪里出错了:
bootstrap.php(phpunit引导文件)
这基本上只是 $app 对象的容器。我使用启动实际应用程序的相同文件(路由、配置)启动 $app 对象。
<?php
/**
* This makes our life easier when dealing with paths. Everything is relative
* to the application root now.
*/
chdir(dirname('../'));
// require composer autoloader for loading classes
require 'vendor/autoload.php';
// app container class - singleton pattern
class App
{
// Hold an instance of the class
private static $instance;
public static function getInstance()
{
if (!isset(self::$instance)) {
// Instantiate a Slim application:
$app = new \Slim\Slim(array(
'mode' => getenv('APPLICATION_ENV') ?: 'production',
));
// set configuration
require 'app/config.php';
// include the routes (always after we've instantiated our app instance)
require 'app/routes.php';
self::$instance = $app;
}
return self::$instance;
}
}
接下来是我的测试文件,其中包含一个测试:
AccountsControllerTest.php
<?php
use Slim\Environment;
class AccountsControllerTest extends PHPUnit_Framework_TestCase {
public static function get($path)
{
Environment::mock(array(
'REQUEST_METHOD' => 'GET',
'PATH_INFO' => $path,
));
$app = App::getInstance();
//$app->middleware[0]->call();
$app->response()->finalize();
return $app->response();
}
public function testIndex() {
$response = $this->get('/accounts');
$this->assertContains('Accounts', $response->getBody());
}
}
希望我想做什么有点清楚。基本上只需检查“帐户”是否存在(当我在浏览器中加载时,该帐户就存在)
下面是我返回的结果:
$ vendor/bin/phpunit
PHPUnit 4.3.4 by Sebastian Bergmann.
Configuration read from /var/www/shared-views-slim/phpunit.xml
F
Time: 33 ms, Memory: 4.75Mb
There was 1 failure:
1) AccountsControllerTest::testIndex
Failed asserting that '' contains "Accounts".
/var/www/shared-views-slim/tests/app/controllers/AccountsControllerTest.php:30
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
UPDATE:
路线.php
<?php
// Define a HTTP GET route:
$app->group('/accounts', function () use ($app) {
$controller = new App\Controllers\AccountsController($app);
// index
$app->get('/', function () use ($controller) {
$controller->index();
});
// show
$app->get('/:id', function ($id) use ($controller) {
$controller->show($id);
})->conditions(array('id' => '[1-9]([0-9]*)'));
// create
// form
$app->get('/create', function () use ($controller) {
$controller->create();
});
// action
$app->post('/', function () use ($controller) {
$controller->create();
});
// update
// form
$app->get('/:id/edit', function ($id) use ($controller) {
$controller->update($id);
})->conditions(array('id' => '[1-9]([0-9]*)'));
// action
$app->put('/:id', function ($id) use ($controller) {
$controller->update($id);
});
// delete
// form
$app->get('/:id/delete', function ($id) use ($controller) {
$controller->delete($id);
})->conditions(array('id' => '[1-9]([0-9]*)'));
//action
$app->delete('/:id', function ($id) use ($controller) {
$controller->delete($id);
});
});