【问题标题】:How to test a controller function using phpunit如何使用 phpunit 测试控制器功能
【发布时间】:2021-07-21 04:37:35
【问题描述】:

我正在学习使用 PHP 进行测试,我需要测试一个返回视图的函数,但我仍然找不到执行此操作的方法。例如下面的函数:

public function getEmails(){
    if (Defender::hasPermission("users")) {
        $index = $this->diretorioPrincipal;
        $route = $this->nameView;

        return view("{$this->index}.{$this->nameView}.emails", compact('index', 'route'));
    } else {
        return redirect("/{$this->index}");
    }
}

谁能解释一下如何测试这个功能?

【问题讨论】:

    标签: php laravel unit-testing phpunit


    【解决方案1】:

    您需要使用php artisan make:test <TestName> 创建一个测试。之后在您的测试中,您通常会调用 setup 方法来初始化一般值。 (可能是用户或模型) 我不知道你的方法的路径,所以假设它是route('myMethod'),你还必须使用 2 个不同的用户:$user1$user2 一个应该有权限users,一个不应该有它,这样两种情况都经过测试。

    class SomeControllerTest extends TestCase
    {
        /** 
        * Setup stuff
        **/
        public function setUp(): void
        {
            parent::setUp();
        }
       //All tests must be written as test<SomeName>
       public function testMyFunction()
        {
           //user1 does have the permission
           $response = $this->actingAs($user1)->get(route('myFunction'));
           //the view response has code status 200 so we will check if the response is ok = 200
           $resp->assertOk();
           
           //user2 does not have the permission
           $response = $this->actingAs($user2)->get(route('myFunction'));
           //the redirect response is has status code 302 so we will check if the response is a redirect = 302
           $resp->assertRedirect();
        }
    }
    

    这是一些基本方法,但我尝试结合您的方法。如果有任何不清楚的地方,请继续询问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-24
      • 2015-06-07
      • 1970-01-01
      • 2013-07-08
      • 1970-01-01
      • 2021-05-03
      相关资源
      最近更新 更多