繁体   English   中英

在Laravel 4中使用Mockery模拟自定义类

[英]Mocking a custom class with Mockery in Laravel 4

使用Laravel 4.2,我在/app/libraries有一个自定义类TestyClass

我正在尝试使用Mockery和PHPUnit模拟该类,但我的Mock似乎没有注册。

当我运行测试时,我得到Mockery\\Exception\\InvalidCountException: Method testymethod() from Mockery_0_TestyClass should be called exactly 1 times but called 0 times.

我正在测试的Controller运行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的新类,添加模拟等所需的行为,然后创建它的实例并返回它,因此$ mock是Mockery_0_TestyClass的实例。

然后,您要告诉嘲笑您希望该实例接收到对testymethod的调用,但实际上您是在对TestyClass类方法进行静态调用。 您可以通过嘲弄来做到这一点,但这并不是很好,我不建议您这样做,您可能希望使用进程隔离来运行测试。

$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是在模拟对象上设置一个侦听器,它正在等待方法运行-如果运行该方法,则一切正常,否则将收到InvalidCountException。

希望对您有帮助,祝您有美好的一天。

我遇到过类似的问题:班级未被认可。 尝试使用__construct方法对其进行初始化。 那对我有用。 (在setUp方法中设置它无效)。

public function __construct()
{
    $this->mock = Mockery::mock('TestyClass');
}

然后只需调用测试方法:

$this->mock->shouldReceive('testymethod')->once();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM