Home >Backend Development >PHP Tutorial >php 单元测试 phpunit ,如何mock类调用自身的方法?

php 单元测试 phpunit ,如何mock类调用自身的方法?

WBOY
WBOYOriginal
2016-06-02 11:31:241931browse

phpunit单元测试phplaravel5

使用laravel5做单元测试时,碰到以下问题,需要测试querySessionIdTest这个方法,
但是需要mock出sessionidtest这个方法,具体代码如下:
类如下:

<code>class ZabbixSystem implements ApmSystemInterface      public function querySessionIdTest()    {        echo 'querySessionIdTest';        return $this->sessionidtest();    }    public function sessionidtest()    {        echo 'sessionidtest';        return 'aaa';    }}</code>

单元测试方法:

<code>public function testQuerySessionIdSuccess()    {        $return = 'aaa';        $stub = Mockery::mock('mcokname');//        $this->app->instance('ZabbixSystem', $stub);        $stub->shouldReceive('querySessionIdTest')->andReturn($return);        $response = $stub->querySessionIdTest();        $this->assertEquals('aaa', $response);    }    public function testQuerySession()    {        // 为 SomeClass 类创建桩件。        $stub = $this->getMockBuilder('App\Services\ZabbixSystem')->setMethods(array(            'querySessionIdTest',            'sessionidtest'        ))->getMock();        // 配置桩件。        $stub->method('sessionidtest')->willReturn('111');        $this->app->instance('ZabbixSystem', $stub);        $this->assertEquals('foo', $stub->querySessionIdTest());    }</code>

通过两种方式进行测试,但都不成功,我希望的结果为:
echo 'querySessionIdTest';
然后测试成功

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn