yan*_* li 5 php phpunit mockery
如何在lumen框架中使用mock?我使用流明框架。Lumen的文档非常简单。我不知道如何使用嘲笑或外观来嘲笑模型。我尝试了一些方法,但没有人奏效。我想在updatePassword方法中模拟UserModel的两点。请帮我。
用户模型
use Illuminate\Database\Eloquent\Model;
class UserModel extends Model {
// connection
protected $connection = 'db_user';
// table
protected $table = 'user';
// primarykey
protected $primaryKey = 'id';
}
Run Code Online (Sandbox Code Playgroud)
用户逻辑
class UserLogic {
public static updatePassword($id, $password) {
// find user
$user = UserModel::find($id); // mock here**************************************
if (empty($user)) {
return 'not find user';
}
// update password
$res = UserModel::where('id', $id)
->update(['password' => $password]); // mock here*****************************
if (false == $res) {
return 'update failed';
}
// re Login
$res2 = LoginModel::clearSession();
if (false == $res2) {
return false;
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
phpunit 测试 1 不起作用
use Mockery;
public function testUpdatePassword() {
$mock = Mockery:mock('db_user');
$mock->shouldReceive('find')->andReturn(false);
$res = UserLogic::updatePassword(1, '123456');
$this->assertEquals('not find user', $res);
}
Run Code Online (Sandbox Code Playgroud)
PHP单元测试2
// BadMethodCallException: Method Mockery_0_Illuminate_DatabaseManager::connection() does not exist on this mock object
use Illuminate\Support\Facades\DB;
public function testUpdatePassword() {
DB::shouldReceive('select')->andReturnNull();
$res = UserLogic::updatePassword(1, '123456');
$this->assertEquals('not find user', $res);
}
Run Code Online (Sandbox Code Playgroud)
phpunit 测试 3 不起作用
use Mockery;
public function testUpdatePassword() {
$mock = Mockery::mock('alias:UserModel');
$mock->shouldReceive('find')->andReturn(null);
$res = UserLogic::updatePassword(1, '123456');
$this->assertEquals('not find user', $res);
}
Run Code Online (Sandbox Code Playgroud)
小智 1
尝试这个:
$mock = Mockery::mock('alias:\NamespacePath\To\UserModel');
$mock->shouldReceive('find')->andReturn(null);
$this->app->instance('\NamespacePath\To\UserModel', $mock);
Run Code Online (Sandbox Code Playgroud)
请注意,当您想要模拟公共静态函数时,请使用关键字alias。如果您想模拟一个对象(使用 创建new),则可以使用关键字overload(What is the Difference between override and alias in Mockery?)。
我在使用模拟时遇到的另一个困难是,我们仍然在其他测试中使用它们,而我不想再使用模拟,这使得测试失败。模拟持久性与类的加载有关。这种情况在全局范围内发生一次,并一直持续到测试过程终止(从这里: https: //blog.gougousis.net/mocking-static-methods-with-mockery/)。因此,无论先发生什么(将类用作模拟或真实的类)都将定义该类的调用方式,之后您将无法再更改它。在我之前链接的博客文章中,Alexandros Gougousis 讨论了如何通过在自己的进程中运行模拟测试并禁用全局状态保存来规避此问题。我尝试了他的方法,但遇到了一些问题,但我也没有花太多时间。为什么不?因为我找到了不同的解决方案:在phpunit.xml设置变量processIsolation="true". 这解决了问题。我应该注意到,这使每次测试的持续时间增加了大约。0.5s,所以如果你让它运行,Alexandros 方法可能会更有效,因为它只会在自己的进程中运行带有模拟的测试。
旁注:这也适用于 Lumen TestCase 作为测试的基类。
| 归档时间: |
|
| 查看次数: |
1510 次 |
| 最近记录: |