Laravel package test

时间:2016-08-31 17:24:54

标签: php laravel phpunit mockery

Hi everyone I'm creating a Laravel package and I'm trying to implement the tests.

My composer.json has this structure:

"require-dev": {
    "graham-campbell/testbench": "^3.1",
    "mockery/mockery": "^0.9.4",
    "phpunit/phpunit": "^4.8|^5.0"
},

I'm using this package for the test creation. I've looked at other packages of Graham Campbell in order to understand a little better how he creates the tests and I'm trying to "adapt" his classes for my goals.

The problem is that I receive this error when running phpunit:

1) IlGala\Tests\LaravelWizzy\WizzyTest::testGetPrefix
Mockery\Exception\NoMatchingExpectationException: No matching handler found for Mockery_0_Illuminate_Contracts_Config_Repository::get("wizzy.prefix", ""). Either the method was unexpected or its arguments matched no expected argument list for this method

/home/ilgala/NetBeansProjects/laravelWizzy/packages/ilgala/laravel-wizzy/vendor/mockery/mockery/library/Mockery/ExpectationDirector.php:93
/home/ilgala/NetBeansProjects/laravelWizzy/packages/ilgala/laravel-wizzy/src/Wizzy.php:68
/home/ilgala/NetBeansProjects/laravelWizzy/packages/ilgala/laravel-wizzy/tests/WizzyTest.php:71

I'm trying to test the Wizzy class which is registered as singleton in the WizzyServiceProvider:

$this->app->singleton('wizzy', function (Container $app) {
    $config = $app['config'];

    return new Wizzy($config);
});

This is my test class:

protected $defaults = [
    [...]
];

/**
 *
 */
public function testGetPrefix()
{
    $wizzy = $this->getWizzy();

    $this->assertSame('install', $wizzy->getPrefix());
}

protected function getWizzy()
{
    $repository = Mockery::mock(Repository::class);

    $wizzy = new Wizzy($repository);

    $wizzy->getConfig()->shouldReceive('get')->once()
            ->with('wizzy.prefix')->andReturn($this->defaults['prefix']);

    return $wizzy;
}

An finally this is the Wizzy class:

/**
 * Config repository.
 *
 * @var \Illuminate\Contracts\Config\Repository
 */
protected $config;

/**
 * Creates new instance.
 */
public function __construct(Repository $config)
{
    $this->config = $config;
}

/**
 * Get the config instance.
 *
 * @return \Illuminate\Contracts\Config\Repository
 */
public function getConfig()
{
    return $this->config;
}

/**
 * Get the configuration name.
 *
 * @return string
 */
protected function getConfigName()
{
    return 'wizzy';
}

/**
 * Get wizzy route group prefix from the config file.
 *
 * @return string wizzy.prefix
 */
public function getPrefix()
{
    return $this->config->get($this->getConfigName() . '.prefix', '');
}

Can anyone help me understand what am I doing wrong?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案......

$wizzy->getConfig()->shouldReceive('get')->once()
        ->with('wizzy.prefix')->andReturn($this->defaults['prefix']);

问题在于此处,因为(使用自然语言翻译此方法),模拟对象应该使用wizzy.prefix字符串调用get方法,但实际上它正在接收wizzy.prefix和{{1所以我用这种方式更改了代码:

''