Reputation: 26534
Note: I am attempting to stub out a \HTML5 object for use within one of my tests.
When mocking the loadHTML()
method and setting a return value, the value is returned as NULL.
/** Set up my expectations **/
$stub = $this->getMock("\HTML5");
$stub->expects($this->once())
->method("loadHTML")
->with("some data")
->will($this->returnValue("Some Value"));
The above sets up the expectation that calling \HTML5::loadHTML("some data")
will return the string Some Value
. Let's call this method.
var_dump($stub->loadHTML("some data")); // NULL
Calling loadHTML()
shows NULL
as the return value.
Why is my expected value not being returned? Is this a bug? An issue with the library I am using?
The \HTML5
object does not have a specific constructor implementation, so I do not need to call disableOriginalConstructor()
on the $stub
object to bypass this.
The loadHTML()
method only takes a string as it's parameter, which I am including.
I am using:
Upvotes: 2
Views: 156
Reputation: 26534
The loadHTML()
method is a static method. In PHPUnit, you do not set up mock static method expectations with expects()
; you must use staticExpects()
instead.
The reason this was not immediately prelevant is because PHP allows static methods to be called as one would do a normal method if the object encapsulating those methods has been instantiated.
I had already created the \HTML5
object, hence the static method could be called with a ->
instead of the usual ::
you can use without object instantiation.
In 2010, Sebastian Bermann wrote a post describing a new staticExpects()
method available in PHPUnit 5.3+.
Here is the code above re-written to use the static method:
$stub = $this->getMock("\HTML5");
$stub->staticExpects($this->once())
->method("loadHTML")
->with("some data")
->will($this->returnValue("Some Value"));
var_dump($stub->loadHTML("some data")); // "Some Value"
In conclusion, just don't write static methods in your own code. It will make other developer's testing (like mine) much harder to deal with having to go into the source code of an external library to understand why I couldn't test my code by mocking out theirs.
Upvotes: 2