我有一个小型的中间件,我想为它编写一个测试..我想做两个测试:
如何做到这一点?
namespace App\Http\Middleware;
use Closure;
use Auth;
use Redirect;
class RedirectIfNotAdminUser {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
if (Auth::user()->role_id != config('Roles.admin')) {
return Redirect::action('Auth\AuthController@getLogin');
}
return $next($request);
}
}
目前我运行的测试如下:
public function testIsAdminUser() {
$user = factory(App\User::class)->make(['role_id' => '1']);
$this->be($user);
$response = $this->action('GET', 'admin\DashboardController@index');
$this->assertEquals(200, $response->getStatusCode());
}
我还必须在设置中添加一行,没有它$ this-> be()不起作用
public function setUp() {
$this->refreshApplication();
}
他们是更好的方法吗?
答案 0 :(得分:0)
试试这个:
public function setUp()
{
$this->redirectIfNotAdminUser = new App\Http\Middleware\RedirectIfNotAdminUser;
}
public function testIsAdminUser()
{
// create a $user object (using a factory or something else).
// assuming $user has a property role_id = 1.
$this->actingAs($user);
// create a mock of $request and $next.
$response = $this->redirectIfNotAdminUser->handle($request, $next);
$this->assertEquals(200, $response->getStatusCode());
}
public function testIsNotAdminUser()
{
// create a $user object (using a factory or something else).
// assuming $user has a property role_id = 2.
$this->actingAs($user);
// create a mock of $request and $next.
$response = $this->redirectIfNotAdminUser->handle($request, $next);
$this->assertEquals(302, $response->getStatusCode());
}
我相信中间件会返回状态代码为200
的响应,如果它是OK
和302
,则会返回。
请记住,您将成为创建User
实例并让其登录的人(使用actingAs()
方法)并且您将成为创建模拟人员的人$request
和$next
将传递给您的中间件handle()
方法。