如何在Laravel 4中模拟Auth类? [英] How do I mock the Auth class in Laravel 4?

查看:77
本文介绍了如何在Laravel 4中模拟Auth类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使我的AuthController可测试.我首先注入Auth类,以便可以在测试中对其进行模拟:

I'm trying to make my AuthController testable. I start by injecting the Auth class so I can mock it in my test:

public function __construct(Auth $auth)
{
    $this->auth = $auth;
}

然后稍后在检查登录是否成功时使用注入的类:

Then I use the injected class later when I check if the login succeeded:

public function postLogin()
{
    // instead of Auth::attempt(Input::all())
    if ($this->auth->attempt(Input::all()) {
        return 'you are logged in!';
    } else {
        return 'login failed!';
    }
}

提交登录表单时,出现错误,提示未定义Auth::attempt方法:

When I submit my login form I get an error that the Auth::attempt method is not defined:

FatalErrorException: Error: Call to undefined method Illuminate\Support\Facades\Auth::attempt() ...

我做错了什么?我看到了模型中使用的精确技术,但显然它不适用于Auth类.

What am I doing wrong? I saw this exact technique used in models, but apparently it's not working for the Auth class.

推荐答案

好吧,您在这里可能做错了...

Well, you might be doing it wrong here...

定义一个模拟Auth Adapter并配置Auth以在测试中使用 that .在Controller中使用Auth的静态方法就可以了.

Define a mock Auth Adapter and configure Auth to use that in tests. Using Auth's static methods in Controllers is just fine.

Auth包实现具有Auth类作用的驱动程序(也称为适配器)模式作为整个程序包的依赖项管理器和单例接口.而不是尝试将模拟Auth实例注入到控制器中,您应该实现模拟Auth Adapter(例如默认的Eloquent和Fluent适配器).另外,在测试过程中,请尝试配置您的身份验证以使用内存适配器.在手册页上(针对懒惰的人)使用 emphasis 我的:

The Auth package implements a Driver (aka Adapter) pattern with the Auth class acting as the dependency manager and singleton interface for the whole package. Instead of trying to inject a mock Auth instance into your controller, you should implement a mock Auth Adapter (like the default Eloquent and Fluent adapters). Also try configuring your Auth to use the In-Memory Adapter while in tests. From the manual page (for the lazy) with emphasis mine:

内存会话

内存"会话驱动程序仅使用一个简单的数组来存储当前请求的会话数据. 该驱动程序非常适合于对应用程序进行单元测试,因为没有任何内容写入磁盘.永远不要将其用作真正的"会话驱动程序.

The "memory" session driver just uses a simple array to store your session data for the current request. This driver is perfect for unit testing your application since nothing is written to disk. It shouldn't ever be used as a "real" session driver.

内存适配器只是一个内存阵列,由于您的测试与被测系统(SUT)共享线程,因此您可以从测试代码中自由检查会话的内容,以验证其副作用.身份验证和后置条件.

The memory adapter is just an in-memory array, and since your tests are sharing threads with your System Under Test (SUT), you can freely inspect the content of the session from within your test code to verify side-effects of authentication and post-conditions.

这篇关于如何在Laravel 4中模拟Auth类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆