Php 在Laravel 4中使用mockry模拟自定义类
使用Laravel4.2,我在Php 在Laravel 4中使用mockry模拟自定义类,php,unit-testing,laravel,phpunit,mockery,Php,Unit Testing,Laravel,Phpunit,Mockery,使用Laravel4.2,我在/app/libraries中获得了一个自定义类TestyClass 使用mockry和PHPUnit,我试图模拟这个类,但我的模拟似乎没有注册 当我运行测试时,我从mockry\u 0\u TestyClass中得到mockry\Exception\InvalidCountException:Method testymethod(),应该精确调用1次,但调用0次。 我正在测试的控制器运行TestyClass::testymethod(),并且testymethod
/app/libraries
中获得了一个自定义类TestyClass
使用mockry和PHPUnit,我试图模拟这个类,但我的模拟似乎没有注册
当我运行测试时,我从mockry\u 0\u TestyClass中得到mockry\Exception\InvalidCountException:Method testymethod(),应该精确调用1次,但调用0次。
我正在测试的控制器运行TestyClass::testymethod()代码>,并且testymethod()
中的Log::info运行正常
在Laravel 4.2中注册自定义类的模拟我缺少什么?
$mock = Mockery::mock('TestyClass');
$mock->shouldReceive('testymethod')->once();
TestyClass:
class TestyClass {
public static function testymethod() {
Log::info('----=-=-=-=--=in heyhey!@!!=-=-=-=-=-=-=-12312312312312341');
return true;
}
}
此代码:
$mock = Mockery::mock('TestyClass');
创建一个新类,该类扩展TestyClass
,添加模拟etc所需的行为,然后创建并返回它的实例,因此$mock是mockry\u 0\u TestyClass的实例
然后,您告诉mockry您希望该实例接收对testymethod
的调用,但实际上是对TestyClass
类方法进行静态调用。您可以使用mockry来实现这一点,但这不是很好,我不建议您这样做,您可能希望使用进程隔离来运行测试
$mock = Mockery::mock('alias:TestyClass');
你在给你的调度员打电话吗?
测试类方法和测试控制器是有区别的。
如果您正在测试控制器,请尝试使用$this->call
-示例
class TestyClassTest extends TestCase {
public function setUp()
{
$this->mock = $this->mock('TestyClass');
}
/* Move method to TestCase.php */
public function mock($class)
{
$mock = Mockery::mock($class);
$this->app->instance($class, $mock);
return $mock;
}
/* Move method to TestCase.php */
public function tearDown()
{
Mockery::close();
}
public function testIfTestyControllerRunsTestyMethodAndReturnsOk()
{
// Step 3. Arrange
// Last we arrange our test
$this->mock->shouldReceive('testymethod')->once();
// Step 2. Act
// Then we write how we the results will be asserted.
// The route should correspond with the controller executing the class method.
// Eg. TestyMethodController@test; return $this->class->testymethod()
**$this->call('GET', 'TestyController@test');**
// Step 1. Assert
// Start by writing the results we expect;
// If the controller issues no Exceptions we should get a response header status 200.
$this->assertResponseOk();
}
}
本质上,$mock->shouldReceive正在mock对象上设置一个侦听器,它正在等待该方法的运行-如果它运行,那么一切都正常,否则您将得到InvalidCountException
希望对你有所帮助,祝你有个愉快的一天。我也遇到过类似的问题:班级没有被认出来。尝试使用_构造方法初始化它。这对我很管用。(在设置方法中设置它不起作用)
然后调用测试方法:
$this->mock->shouldReceive('testymethod')->once();
是的,正如您所说的,它不是很好,别名对我的虚拟TestyClass有效,但是当应用到我的真实且广泛的Lib
类时,它崩溃了:PHP致命错误:调用成员函数\uu Call()在/Users/lukeshaheen/Dropbox/WWW/Phone2Action 2.0/vendor/mockry/mockry/library/mockry/Loader/EvalLoader.php(16)中的非对象上:eval()'d第633行的代码
。
$this->mock->shouldReceive('testymethod')->once();