【发布时间】:2020-06-08 02:39:11
【问题描述】:
我正在尝试对具有“create()”方法的“AdminService”类进行单元测试,并且在构造函数中我需要一个依赖项,即 AdminRepository 。
我使用 mockery 来模拟存储库并将这个模拟传递给 AdminService _contsruct() 但是当我运行测试时出现错误:错误:Call to a member function create() on null
这是我要测试的 AdminService : 我关注了这篇文章:Unit tests – complex argument matching with Mockery::on – the right way
use App\Repositories\AdminRepository;
class AdminService {
protected $admin_repo;
public function _contsruct(AdminRepository $admin_repo){
$this->$admin_repo= $admin_repo;
}
public function create($data){
return $this->admin_repo->create($data);
}
}
测试代码是:
/** @test */
public function it_can_create_Admin(){
$data=[
"first_name"=>"lama",
"last_name"=>"sonmez",
"email"=>"lamasonmez@gmail.com",
"password"=>"secret"
];
$repo_mock = Mockery::mock(AdminRepository::class);
$repo_mock->shouldReceive('create')->once()->with($data)
->andReturn('anything');
$admin_service = new AdminService($repo_mock);
$admin = $admin_service->create($data);
$this->assertInstanceOf(Admin::class,$admin);
}
我不知道这里出了什么问题,请帮忙。
当我 dd($repo_mock) 给我模拟时,我的意思是它不为空
但是当我 dd($admin_service) 我得到了
App\Services\AdminService^ {#4106
#admin_repo: null
}
【问题讨论】:
标签: php laravel unit-testing phpunit mockery