如何在模拟对象中设置变量

Enr*_*que 8 php oop phpunit unit-testing mocking

有没有办法在模拟对象中设置类级变量?

我有类似于这样的模拟对象:

$stub = $this->getMock('SokmeClass', array('method'));
$stub->expects($this->once())
         ->method('method')
         ->with($this->equalTo($arg1));
Run Code Online (Sandbox Code Playgroud)

赢得真正的类有一个变量需要设置才能正常工作.如何在模拟对象中设置该变量?

vvk*_*wss 16

这对我有用:

$stub = $this->getMock('SomeClass');
$stub->myvar = "Value";
Run Code Online (Sandbox Code Playgroud)


小智 5

不知道为什么这样有效但似乎对我而言.如果你将__get魔术方法作为重写方法之一,例如

$mock = $this->getMock('Mail', array('__get'));
Run Code Online (Sandbox Code Playgroud)

那么你可以成功地做到

$mock->transport = 'smtp';
Run Code Online (Sandbox Code Playgroud)


Gor*_*don 3

存根的想法是用测试替身替换依赖项,提供相同的方法接口(可选)返回配置的返回值。这样,SUT 就可以像依赖一样使用 double 了。如果您需要存根的特定返回值,您只需告诉它应该返回什么,例如:

// Create a stub for the SomeClass class.
$stub = $this->getMock('SomeClass');

// Configure the stub.
$stub->expects($this->any())
     ->method('doSomething')
     ->will($this->returnArgument(0));

$stub->doSomething('foo'); // returns foo
Run Code Online (Sandbox Code Playgroud)

请参阅http://www.phpunit.de/manual/current/en/test-doubles.html