以下是我正在处理的控制器的简化类:
class UserController extends Controller {
protected $user;
public function __construct(User $user) {
$this->user = user;
}
public function contact(ContactFormRequest $request) {
$user = $this->user
->where('email', $request->email)
->with(['orders' => function($q) {
$q->orderBy('created_at', 'desc')
->first();
}])
->first();
return view('contact', ['user' => $user]);
}
}
这是我到目前为止的测试案例:
class ExampleTest extends TestCase {
public function setUp () {
$this->mockUser = Mockery::mock(Model::class, User::class);
$this->app->instance('User', $this->mockUser);
}
public function testContactForm() {
$this->userMock
->shouldReceive('where')
->once()
->with('email', 'fake@email.com')
->andReturn(new Collection(new User, new User));
$this->visit('contact-form');
}
}
我承认我是从记忆中写的,而不是把现有的代码放在我面前。但是这项测试正在通过PHPUnit。问题是访问会引发错误,我需要进行额外的->see('something')
测试。
我需要模拟的其余部分,它为控制器和视图提供了一个完整且可用的用户模拟。
我希望它看起来像(这是代码出错的地方)
$this->userMock
->shouldReceive('where')
->once()
->with('email', 'fake@email.com')
->andReturn(new Collection(new User))
->shouldReceive('with')
->once();
->with(['orders' => function($q) {
$q->orderBy('created_at', 'desc')
->first();
}])
->andReturn( **something** )
->shouldReceive('first')
->once()
->andReturn(new Collection(new User));
答案 0 :(得分:0)
不要嘲笑ORM(知道Don't mock third-party libraries或只知道你拥有的模拟类型)。相反,提供一个测试数据库(使用fixture或 afactory),这样代码实际上找到了你想要的用户