【问题标题】:Testing method with dependency and partial mock PhpUnit具有依赖和部分模拟 PhpUnit 的测试方法
【发布时间】:2014-03-26 01:40:11
【问题描述】:

我在测试这个简单的方法时遇到了一些问题。

我使用属于要测试的类的方法检查是否存在对话,然后使用依赖项的方法删除该对话。

问题是,在我测试了方法 remove 之后,我无法弄清楚如何传递模拟的依赖项,因为我已经模拟了主类来测试传递它的依赖项,以确保该类是部分模拟的。

这是我原来的方法

    <?php

    /**
    * Remove the current user to be fan the current team
    *
    * @param $user_id (int) | current user id
    * @param $team_id (int) | current team id
    * @return bool | true | false
    */
    public function remove($user_id, $team_id) {

        try 
        {
            $fan = $this->check($user_id,$team_id);
            $this->fan->delete($fan->id); // this->fan is the dependency on my constructor
            return true;
        } 
        catch(FanNotFoundException $e) 
        {
            $this->errors = $e->message();
            return false;
        }

    }

我的测试给我一个错误:

test_remove_fan_from_db 试图获取非对象的属性

我猜是因为。在测试依赖项的删除方法之前,我部分模拟了主类,但我认为没有其他方法可以部分模拟主类“团队”来测试检查方法。但是然后我必须将测试的删除方法传递给该类。怎么样?

<?php

public function test_remove_fan_from_db() {

        $mockInterface = m::mock('Core\Social\Fan\Repository\FanTeamRepositoryInterface');
        $mocked = m::mock('Core\Social\Fan\Entity\Team[check]',[$mockInterface]);

        $mocked->shouldReceive('check')
                        ->with(1,2)
                        ->once()
                        ->andReturn(true);

        $mockInterface->shouldReceive('delete')
                            ->with(1)
                            ->andReturn(true);

        $team = $mocked->remove(1,2);

        $this->assertTrue( $team );
    }

【问题讨论】:

    标签: unit-testing mocking phpunit mockery


    【解决方案1】:

    我犯了一个初学者的错误,我这样解决了:

    public function test_remove_fan_from_db() {
    
            $mockInterface = m::mock('Core\Social\Fan\Repository\FanTeamRepositoryInterface');
    
            $mockInterface->shouldReceive('delete')
                                ->once()
                                ->andReturn(true);
    
            $mocked = m::mock('Core\Social\Fan\Entity\Team[check]',[$mockInterface]);
    
            $mocked->shouldReceive('check')
                            ->with(1,2)
                            ->once()
                            ->andReturn(new Fans);
    
            $team = $mocked->remove(1,2);
    
            $this->assertTrue( $team );
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      • 2016-02-06
      • 1970-01-01
      • 2010-10-07
      • 1970-01-01
      相关资源
      最近更新 更多