Home » Software Development

Testing protected methods in SilverStripe

14 May 2013 No Comment

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);

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.

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