ekvedaras/laravel-test-helpers

此包已被废弃,不再维护。没有建议的替代包。

Laravel应用程序测试的各种辅助工具

v1.1.0 2018-09-26 11:43 UTC

This package is auto-updated.

Last update: 2022-02-01 13:14:22 UTC


README

Latest Version Build Status Quality Score Coverage Status StyleCI Total Downloads

在每天编写测试时,某些操作可能会重复多次,让人感到厌烦。此包提供了解决这些问题的方案,并有助于更快、更整洁地编写测试。它不强制执行任何操作。构建模拟和期望的主要方式仍然可以在合理的地方使用。

变更日志

安装

composer require ekvedaras/laravel-test-helpers --dev

使用方法

只需在您的测试类中使用TestHelpers特质(或您希望明确提供的其他任何特质)。

辅助工具

TestHelpersMock

提供辅助方法,可以更快速地定义PHPUnit模拟期望。

注意:要创建此模拟,必须使用BuildsMocks@mock一次

  • 两次
  • times
  • any
  • consecutiveTwice
  • consecutive
  • never
  • fail
  • fail

BuildsMocks特质

创建模拟并将它们注入到Laravel中,这样使用app(My::class)时,模拟会被解析而不是使用实际实例,并且当容器自动解析注入器的构造函数参数时也是如此。

// Creates PhpUnit mock wrapped with TestHelpersMock 
$this->mock($mockClass, $injectorClass, $methods, $constructorArgs, $onlyForInjector);

// Creates Mockery mock
$this->mockery($mockClass, $injectorClass, $onlyForInjector);

// Creates spy mock
$this->spy($mockClass, $injectorClass, $onlyForInjector);

注意:只需要第一个参数

ChecksSingletons特质

检查给定的类是否标记为单例。

$this->assertSingleton(My::class);

TestsCommands特质

为给定的命令类创建命令测试器。

$tester = $this->getCommandTester(MyCommand::class);
$tester->execute($input);
$out = $tester->getDisplay();

TestsHelpers特质

这是一个方便的特质,它包含上面提到的所有特质。

示例

更多示例可以在包测试中找到。

使用TestHelpersMock进行模拟期望

use BuildsMocks;

$mock = $this->mock(My::class);


// Using helpers
// Equivalent


$mock->once('someMethod');
$mock->expects($this->once())->method('someMethod');

$mock->once('someMethod', $foo, $bar);        
$mock->expects($this->once())->method('someMethod')->with($foo, $bar);

$mock->twice('someMethod', $foo, $bar);
$mock->expects($this->exactly(2))->method('someMethod')->with($foo, $bar);

$mock->times(3, 'someMethod', $foo, $bar)->willReturn(true);
$mock->expects($this->exactly(3))->method('someMethod')->with($foo, $bar)->willReturn(true);

$mock->any('someMethod', $foo, $bar);
$mock->expects($this->any())->method('someMethod')->with($foo, $bar);

$mock->consecutiveTwice('someMethod', [$foo], [$bar]);
$mock->expects($this->exactly(2))->method('someMethod')->withConsecutive([$foo], [$bar]);

$mock->consecutive(3, 'someMethod', [$foo], [$bar], [$foo, $bar]);
$mock->expects($this->exactly(3)->method('someMethod')->withConsecutive([$foo], [$bar], [$foo, $bar]);

$mock->never('someMethod');
$mock->expects($this->never())->method('someMethod');

$mock->fail('someMethod', new \Exception());
$mock->expects($this->any())->method('someMethod')->willThrowException(new \Exception());

$mock->fail('someMethod', new \Exception(), $foo, $bar);
$mock->expects($this->any())->method('someMethod')->with($foo, $bar)->willThrowException(new \Exception());