i want to run phpunit test in controller for
adding some data in database and testing api of project both
PostAddTest类
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
class PostAddTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testExample()
{
$api = "/post/add";
$request = [
'title' => "xyz form....",
'content' => 'post add by xyz user.'
];
$response = $this->postJson($api,$request);
info("daa : ".print_r($response->getContent(),true));
$this->assertTrue(true);
}
}
如果我使用phpunit运行,则成功工作
vendor/phpunit/bin --filter testExample
PHPUnit 6.5.5 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 6.84 seconds, Memory: 28.00MB
OK (1 test, 1 assertion)
我成功了,但是
如果我使用控制器运行,则会出现这样的错误
在null {“ exception”:“ [object]上调用成员函数make() (Symfony \ Component \ Debug \ Exception \ FatalThrowableError(代码:0): 在null处调用成员函数make() PostProject / vendor / laravel / framework / src / Illuminate / Foundation / Testing / Concerns / MakesHttpRequests.php:335
MainController
public function index() {
(new PostAddTest)->testExample()
}
答案 0 :(得分:2)
您应该首先调用setUp
方法。像这样:
$postAddTest = new PostAddTest;
$postAddTest->setUp();
$postAddTest->testExample();
我不知道您的用例,但是如果您真的想在控制器中运行测试,作为替代,您可以使用Symfony Process并执行以下操作:
use Symfony\Component\Process\Process;
...
public function index() {
$process = new Process(array('vendor/bin/phpunit', '--configuration', 'phpunit.xml'), base_path());
$process->run();
// (Optional) Get the phpunit output
$process->getOutput();
}
或使用PHP exec()函数http://php.net/manual/en/function.exec.php