Testing protected methods in SilverStripe

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<strong> cleanAndAddDash()</strong> 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);
    }
}

Add a Comment

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image