Reputation: 15115
i want to run phpunit test in controller for
adding some data in database and testing api of project both
PostAddTest class
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);
}
}
if i run using phpunit then successfully worked
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)
i got success but
if i run using controller then i geting error like this
Call to a member function make() on null {"exception":"[object] (Symfony\Component\Debug\Exception\FatalThrowableError(code: 0): Call to a member function make() on null at PostProject/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:335
MainController
public function index() {
(new PostAddTest)->testExample()
}
Upvotes: 1
Views: 3103
Reputation: 451
You should call the setUp
method first. Like this:
$postAddTest = new PostAddTest;
$postAddTest->setUp();
$postAddTest->testExample();
I don't know your use case but if you really want to run your tests in the controller, as alternative you could use Symfony Process and do this:
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();
}
or use PHP exec() function http://php.net/manual/en/function.exec.php
Upvotes: 4