is_callable 在 Mockery::mock() 上总是 returns 真
is_callable on Mockery::mock() always returns true
我的代码分支取决于模拟对象是否有方法。
实际上 class 我有 2 个选项来检查方法是否存在:is_callable
和 method_exists
。
// Defining mocks for test
$emptyMock = m::mock();
$mockWithExpectation = m::mock()
->shouldReceive('foo')
->andReturn('bar')->getMock();
// Trying to perform checks inside of tested class
method_exists($emptyMock, 'foo'); // false
method_exists($mockWithExpectation, 'foo'); // false
is_callable([$emptyMock, 'foo']); // true
is_callable([$mockWithExpectation, 'foo']); // true
让我们在 mock 上调用这些方法。
$emptyMock->foo(); // \BadMethodCallException
$mockWithExpectation->foo(); // 'bar'
如您所见,方法 execute/fail 正确。
是否可以在不经过测试的情况下确定方法是否可调用 class 明确知道他正在处理 mock。
提前感谢您的帮助。
看来我的嘲讽太过分了,因为我需要的功能存在于 vanilla PHPunit 中。
$mock = $this->getMockBuilder(stdClass::class)
//->setMethods(['foo'])
->getMock();
is_callable([$mock, 'foo']); // gives true only if foo is set
我的代码分支取决于模拟对象是否有方法。
实际上 class 我有 2 个选项来检查方法是否存在:is_callable
和 method_exists
。
// Defining mocks for test
$emptyMock = m::mock();
$mockWithExpectation = m::mock()
->shouldReceive('foo')
->andReturn('bar')->getMock();
// Trying to perform checks inside of tested class
method_exists($emptyMock, 'foo'); // false
method_exists($mockWithExpectation, 'foo'); // false
is_callable([$emptyMock, 'foo']); // true
is_callable([$mockWithExpectation, 'foo']); // true
让我们在 mock 上调用这些方法。
$emptyMock->foo(); // \BadMethodCallException
$mockWithExpectation->foo(); // 'bar'
如您所见,方法 execute/fail 正确。
是否可以在不经过测试的情况下确定方法是否可调用 class 明确知道他正在处理 mock。
提前感谢您的帮助。
看来我的嘲讽太过分了,因为我需要的功能存在于 vanilla PHPunit 中。
$mock = $this->getMockBuilder(stdClass::class)
//->setMethods(['foo'])
->getMock();
is_callable([$mock, 'foo']); // gives true only if foo is set