php - How to assert mock object's function invocation's object arguments -
consider
class foo { public $att; public function __construct ( $a ) { $this->att = $a; } } class { public function callme ( foo $f ) {} } // class want test class sut { public function testme ( $s ) { echo $s->callme( new foo('hi') ); } }
i want check whether sut::testme()
invokes some::callme()
. since parameter (foo
) object (not scalar type), can't figure out how call phpunit's with()
run assertions on it. there assertattributeequals
method example, how feed invocation's argument?
what i'd this:
class suttest extends phpunit_framework_testcase { public function testsut () { $stub = $this->getmock( 'some' ); $stub->expects( $this->once() )->method( 'callme' ) ->with( $this->assertattributeequals('hi', 'att', $this->argument(0) ); /* * $stub->callme called foo object $att 'hi'? */ $sut = new sut(); $sut->testme( $stub ); } }
you pass expected values "with" method.
->with(1, $object, "paramthree");
you can pass in range of phpunit assertions instead of parameters (it defaults equal to)
->with(1, $this->equalto($object), "paramthree");
so objects use $this->isinstanceof("stdclass")
parameter ->with
for list of possible assertions into: phpunit/framework/assert.php
for functions return new phpunit_framework_constraint
small demo
the first testcase matches 2 arguments , works
the second 1 matches 2 , fails on argument 2
the last 1 tests passed in object of type stdclass
<?php class mockme { public function bla() { } } class demo { public function foo(mockme $x) { $x->bla(1, 2); } public function bar(mockme $x) { $x->bla(1, new stdclass()); } } class demotest extends phpunit_framework_testcase { public function testworks() { $x = new demo(); $mock = $this->getmock("mockme"); $mock->expects($this->once())->method("bla")->with(1,2); $x->foo($mock); } public function testfails() { $x = new demo(); $mock = $this->getmock("mockme"); $mock->expects($this->once())->method("bla")->with(1,3); $x->foo($mock); } public function testobject() { $x = new demo(); $mock = $this->getmock("mockme"); $mock->expects($this->once())->method("bla")->with(1, $this->isinstanceof("stdclass")); $x->bar($mock); } }
results in:
phpunit demotest.php phpunit 3.5.13 sebastian bergmann. .f. time: 0 seconds, memory: 4.25mb there 1 failure: 1) demotest::testfails failed asserting <integer:2> matches expected <integer:3>. ...demotest.php:12 ...demotest.php:34 failures! tests: 3, assertions: 2, failures: 1.
Comments
Post a Comment