I'm trying to write unit tests for a PHP Wordpress project, but I'm struggling to grasp some of the concepts when it comes to mocking up external function calls and I'm not really sure what I need to do.
Here is a very dumbed down version of the class I have created:
class Module
{
private $title;
public __construct($id = false)
{
$this->title = get_the_title($id); // core wp function
}
public get_title()
{
return $this->title;
}
}
And I want to test it like so:
class ModuleTests extends TestCase
{
public test_get_title_returns_title_if_id()
{
$module = new Module(1);
$this->assertSame($module->get_title(), 'A Test Title'); // should equal true
}
public test_get_title_returns_empty_string_if_no_id()
{
$module = new Module();
$this->assertSame($module->get_title(), ''); // should equal true
}
}
Now obviously this doesn't work in isolation, because Module uses a core wordpress function in the constructor, so what is the correct method for testing in this scenario? Should I be replacing the global get_the_title() function with something that returns a hard coded value if the right arguments are passed to it? or is there some other way of doing this?
I'm trying to drag myself away from the old wordpress procedural style PHP to use some more OOP practices for the bigger projects I work on but I'm still very new to it, so if I'm doing something completely wrong feel free to give constructive critisism as well.
Also, I know that WP already has the template function the_title(), but I'm just using this as a simple example.
Thanks in advance!