【问题标题】:How do I mock this for testing?我如何模拟这个进行测试?
【发布时间】:2017-01-05 07:41:34
【问题描述】:

以下是我正在处理的控制器的简化类:

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));

【问题讨论】:

    标签: php laravel-5 phpunit


    【解决方案1】:

    不要模拟 ORM(称为 Don't mock third-party libraries 或仅模拟您拥有的类型)。而是提供一个测试数据库(带有fixture 或 afactory),这样代码才能真正找到您想要的用户

    【讨论】:

    • 嘿Maxim,我想说理想的控制器测试不应该需要真正的测试数据库。我会将 ORM 封装在一个服务类中,然后在控制器测试中模拟那个。但是,对于服务层类,我会完全按照您的建议进行操作,并使用测试数据库进行测试以确保逻辑确实有效。如果它不在控制器测试范围内,则可以更轻松地添加更多边界测试。
    猜你喜欢
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 2016-05-22
    相关资源
    最近更新 更多