PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, February 1, 2022

[FIXED] how to run phpunit test in laravel controller?

 February 01, 2022     laravel, laravel-5, php, phpunit, unit-testing     No comments   

Issue

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()  
}

Solution

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



Answered By - Erick Patrick
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing