【问题标题】:Assert if returned value is Redirect or View断言返回的值是 Redirect 还是 View
【发布时间】:2015-02-12 21:32:24
【问题描述】:

假设我有这个控制器用于身份验证:

class AuthController extends BaseController
{
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function getLogin()
    {
        if (Auth::check()) {
            Session::flash('alert-type', 'error');
            Session::flash('alert-message', 'You are already logged in');
            return Redirect::to('home');
        }

        return View::make('auth/login');
    }
}

我有这个单元测试:

public function testGetLoginWithoutLogin()
{
    Auth::shouldReceive('check')->once()->andReturn(false);
    View::shouldReceive('make')->once();

    $userMock = Mockery::mock('Eloquent', 'User');

    $authController = new AuthController($userMock);
    $authController->getLogin();
}

我如何确保此处返回一个视图?在具有有效登录名的不同单元测试中,我将如何测试它是否返回重定向?

【问题讨论】:

    标签: unit-testing laravel laravel-4


    【解决方案1】:

    您可以检查getLogin()的返回值的类型。

    用于重定向

    $returnValue = $authController->getLogin();
    $this->assertInstanceOf('\Illuminate\Http\RedirectResponse', $returnValue);
    

    为了观点

    $returnValue = $authController->getLogin();
    $this->assertInstanceOf('\Illuminate\View\View', $returnValue);
    

    【讨论】:

    • 在这种情况下这是不可能的,考虑到 View 和 Redirect 正在被模拟,因此它们不会是这些类中的任何一个的实例。
    • Puhh 老实说,我在 Mockery 上的工作并不多。但是你不应该有一些方法来区分两个模拟对象吗?
    • @DenizZoeteman 你用 instanceof 测试过吗?我以为它也行不通,但我只是做了一点检查,似乎它确实有效。
    • 你究竟是如何模拟视图/响应的? (对不起,如果这听起来有点愚蠢,但我对嘲弄不是很有经验)
    【解决方案2】:

    使用with() 检查您的视图是否获得了正确的模板:

    View::shouldReceive('make')->once()->with('auth/login');
    

    ...然后检查重定向,有一些useful assertions that come built in to Laravel,所以:

    // once you make your simulated request
    $this->call('GET', 'URL-that-should-redirect');
    
    // (or simulate a get to the action on your Controller.. )
    $this->action('GET', 'Controller@action');
    
    //you can check that a redirect simply happens:
    $this->assertResponseStatus(302); // would also work with any HTTP status
    
    // ...or even check that you get redirected to 
    // a particular URL ...
    $this->assertRedirectedTo('foo');
    
    // ... route ...
    $this->assertRedirectedToRoute('route.name');
    
    // ...or controller action
    $this->assertRedirectedToAction('Controller@method');
    

    【讨论】:

    • 问题是,我想进行实际的单元测试——因此,尽可能将函数与框架本身分开测试。我不认为这是你可以使用模拟请求完全完成的事情......
    • @DenizZoeteman 你可以很容易地测试控制器的动作。这有帮助吗?还有一个烘焙方法。我会在上面更新
    猜你喜欢
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    相关资源
    最近更新 更多