如何使用phpunit测试控制器功能
我正在学习使用PHP进行测试,我需要测试一个返回视图的函数,但我仍然找不到一种方法。例如,下面的函数:如何使用phpunit测试控制器功能,php,laravel,unit-testing,phpunit,Php,Laravel,Unit Testing,Phpunit,我正在学习使用PHP进行测试,我需要测试一个返回视图的函数,但我仍然找不到一种方法。例如,下面的函数: public function getEmails(){ if (Defender::hasPermission("users")) { $index = $this->diretorioPrincipal; $route = $this->nameView; return view("{$th
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 artisan make:test创建一个测试。在测试之后,您通常会调用setup方法来初始化常规值。(可能是用户或模型)
我不知道你的方法的路径,所以假设它是路径('myMethod')
,你还必须使用两个不同的用户:$user1
和$user2
一个应该有权限用户
,另一个不应该有权限,以便测试这两种情况
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();
}
}
class SomeControllerTest扩展了TestCase
{
/**
*安装材料
**/
公用函数设置():无效
{
父::设置();
}
//所有测试都必须以测试形式编写
公共函数testMyFunction()
{
//user1没有权限
$response=$this->actingAs($user1)->get(route('myFunction');
//视图响应的代码状态为200,因此我们将检查响应是否为ok=200
$resp->assertOk();
//user2没有该权限
$response=$this->actingAs($user2)->get(route('myFunction');
//重定向响应的状态代码为302,因此我们将检查响应是否为redirect=302
$resp->assertRedirect();
}
}
这是一些基本的方法,但我尝试了合并您的方法。如果有什么不清楚的地方,就继续问下去