Laravel 5.0模型测试Mockery无法模拟方法/静态方法不存在?

时间:2015-06-20 05:27:22

标签: php unit-testing model laravel-5 mockery

我正在使用Laravel 5.0在实际模型旁边创建phpunit测试。 我在phpunit测试中遇到错误,但是当控制器调用模型时它没有错误,它返回了所需的数据。

sample.php

<?php namespace App;
use Illuminate\Database\Eloquent\Model;


class sample extends Model  {


/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'sample';

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['id','username','details','image'];

/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/

public static function test()
{
    return "Returned Text.";
}
public static function gettest()
{
    return self::test();
}

public static function getItem()
{
    return self::orderBy('username','asc')->get();
}

public static function findItem($id)
{
    return self::find($id);
}

}

SampleTest.php

<?php namespace App;

use Mockery as m;

class SampleTest extends \PHPUnit_Framework_TestCase {

protected function setUp()
{
    $this->mock = m::mock('App\sample')->makePartial();
}

protected function tearDown()
{
    m::close(); 
}

/** @test */
public function should_return_string()
{
    $response = $this->mock->test();
    var_dump("test() returns :".$response);
}

/** @test */
public function should_return_string_from_test_function()
{
    $response = $this->mock->gettest();
    var_dump("gettest() returns :".$response);
}

/** @test */
public function should_return_mocked_data()
{
    $this->mock->shouldReceive('test')->andReturn('Return Mocked Data');
    $response = $this->mock->gettest();
    var_dump("gettest() returns :".$response);
}

/** @test */
public function should_return_some_data_using_this_mock()
{
    $this->mock->shouldReceive('get')->andReturn('hello');
    $response = $this->mock->getItem();
}

}

问题 当我使用控制器来调用模型时,它返回了所需的数据。 当我在命令提示符下运行phpunit时: -

  1. test函数未正确模拟,因为它仍然返回原始字符串
  2. getItemfindItem函数返回错误

    1)App \ SampleTest :: should_return_some_data_using_this_mock BadMethodCallException:静态方法Mockery_0_App_sample :: getItem() 在此模拟对象上不存在

  3. 问题 如何正确模拟功能?为什么说错误代码如上所示?我在哪里做错了?

    非常感谢任何帮助。

    注意:删除测试断言并替换为var_dump以在命令提示符下查看输出。

0 个答案:

没有答案
相关问题