我正在创建一个Laravel控制器,其中将随机字符串生成器接口注入其中一种方法。然后在AppServiceProvider中注册一个实现。这很好。
控制器使用随机字符串作为输入将数据保存到数据库。由于它是随机的,因此无法MakesHttpRequests
像这样测试(使用):
$this->post('/api/v1/do_things', ['email' => $this->email])
->seeInDatabase('things', ['email' => $this->email, 'random' => 'abc123']);
因为我不知道使用实际的随机数生成器时将是什么“ abc123”。因此,我创建了Random接口的另一个实现,该实现始终返回“ abc123”,因此可以对此进行断言。
问题是:如何在测试时绑定到该假生成器?我试着做
$this->app->bind('Random', 'TestableRandom');
就在测试之前,但它仍然使用我在AppServiceProvider中注册的实际生成器。有任何想法吗?关于如何测试这样的事情,我是否完全走错了轨道?
谢谢!
您有两种选择:
使用条件绑定实现:
class AppServiceProvider extends ServiceProvider {
public function register() {
if($this->app->runningUnitTests()) {
$this->app->bind('Random', 'TestableRandom');
} else {
$this->app->bind('Random', 'RealRandom');
}
}
}
第二种选择是在测试中使用模拟
public function test_my_controller () {
// Create a mock of the Random Interface
$mock = Mockery::mock(RandomInterface::class);
// Set our expectation for the methods that should be called
// and what is supposed to be returned
$mock->shouldReceive('someMethodName')->once()->andReturn('SomeNonRandomString');
// Tell laravel to use our mock when someone tries to resolve
// an instance of our interface
$this->app->instance(RandomInterface::class, $mock);
$this->post('/api/v1/do_things', ['email' => $this->email])
->seeInDatabase('things', [
'email' => $this->email,
'random' => 'SomeNonRandomString',
]);
}
如果您决定采用模拟路线。确保检查嘲讽文档:
http://docs.mockery.io/en/latest/reference/expectations.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句