【问题标题】:how to run phpunit test in laravel controller?如何在 laravel 控制器中运行 phpunit 测试?
【发布时间】:2018-11-01 13:34:10
【问题描述】:
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

主控制器

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

【问题讨论】:

  • “使用控制器运行”是什么意思?你是通过浏览器手动打开@index方法吗?
  • 通过浏览器在控制器@index方法中运行特定的phpunit测试

标签: php laravel unit-testing laravel-5 phpunit


【解决方案1】:

您应该首先调用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

【讨论】:

  • 我想使用Symfony Process 运行特定测试我该怎么做
  • 添加--过滤testExample到新进程中的数组:array('vendor/bin/phpunit', '--configuration', 'phpunit.xml', '--filter' ,'testExample ')
  • 另外,如果你想在一个特定的目录中执行所有的测试(例如在目录 tests/Unit 中的测试),将数组更改为:array('vendor/bin/phpunit', '--配置','phpunit.xml','测试/单元')
  • 现在发送请求成功但不是等待响应只得到空输出..
猜你喜欢
  • 2016-01-31
  • 2016-01-14
  • 2014-04-30
  • 2014-06-06
  • 1970-01-01
  • 2015-03-24
  • 2017-10-19
  • 2017-08-16
  • 1970-01-01
相关资源
最近更新 更多