This post talks about testing a private method using SilverStripe framework.
Say we have a page FoodPage and a private function cleanAndAddDash.
class FoodPage extends Page { .... protected function cleanAndAddDash($string) { $string = strtolower($string); $string = preg_replace("/[^a-z0-9_\s-]/", "", $string); $string = preg_replace("/[\s-]+/", " ", $string); $string = preg_replace("/[\s_]/", "-", $string); return $string; } }
First I create a mock class, FoodPageTest_Mock which extends FoodPageTest and is only
used for tests.
Then another test class, FoodPageTest is created where the protected method is tested.
Refer to the code below to see how it all works together.
class FoodPageTest extends SapphireTest { .... // tests the protected function cleanAndAddDash() from FoodPage Class. function testCleanAndAddDash() { $foodPageMockObject = new FoodPageTest_Mock; $this->assertEquals($foodPageMockObject->cleanAndAddDash('silver^$ stripe 999283'), 'silver-stripe-999283'); $this->assertEquals($foodPageMockObject->cleanAndAddDash('new ZeaLANd A55 @#%@$#@$#^AIRS'), 'new-zealand-a55-airs'); } } /** * Create a mock class that extends the FoodPage and declare the protected function to be public. * **/ class FoodPageTest_Mock extends FoodPage implements TestOnly { public function cleanAndAddDash($string) { return parent::cleanAndAddDash($string); } }