如何在laravel控制器中运行phpunit测试


i want to run phpunit test in controller for

adding some data  in database and  testing api of project both 

PostAddTest类

namespace TestsFeature;
use TestsTestCase;
use IlluminateFoundationTestingWithFaker;
use IlluminateFoundationTestingRefreshDatabase;
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上调用成员函数make(({"exception":"[object](Symfony\Component\Debug\Exception\FatalThrowableError(代码:0(:在处对null调用成员函数make((PostProject/vender/laravel/framework/src/IIlluminate/Foundation/Testing/Conspects/MakesHttpRequests.php:335

主控制器

public function index() {
(new PostAddTest)->testExample()  
}

您应该首先调用setUp方法。像这样:

$postAddTest = new PostAddTest;
$postAddTest->setUp();
$postAddTest->testExample();


我不知道你的用例,但如果你真的想在控制器中运行测试,作为替代方案,你可以使用Symfony Process并执行以下操作:

use SymfonyComponentProcessProcess;
...
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

最新更新