如何在phpunit中模拟静态变量/属性?

时间:2018-07-10 03:06:15

标签: php phpunit

我想使用phpunit编写php函数测试。

我有一个名为Member的班级:

class Member {
    public static STATUS_DELETED = 'deleted';
    public static STATUS_NORMAL = 'normal';

    private $name;
    private $status;

    public function getName() {
        return $this->name();
    }

    public function getStatus() {
        return $this->status;
    }
}

MemberService类,它是要测试的目标:

class MemberService() {
    public function printMember(Member $member) {
        // Maybe some other logic, it's just a sample

        $status = $member->getStatus();

        // this line will get error when run test!
        if ($status == ‘Member::STATUS_DELETED’) {
            echo "this member " . $member->getName() . " has deleted";
        } else {
            echo $member->getName();
        }
    }
}

还有一个phpunit测试用例:

class MemberServiceTest extends MyUnitTestCase {
    protected function setUp() {
    }

    protected function tearDown() {
    }

    public testPrintMember() {
        $memberService = new MemberService();

        // mock member
        $member = $this->createMock(Member::class);

        $member->method('getName')
            ->willReturn('zhangsan');

        $member->method('getStatus')
            // can not use Member::STATUS_NORMAL in there after mock
            ->willReturn('normal');

        $MemberService->printMember($member);

        // assert some thing in there
    }
}

然后我运行测试,得到错误:Fatal error: Undefined class constant 'STATUS_DELETED' in ...

Member::STATUS_DELETED只是一个const变量,它也可以放在其他位置,但是我不想移动它。

如何模拟静态变量/属性?

0 个答案:

没有答案