awesomeprogrammer.com

Sharing ideas

Solving problems

Gathering solutions

Exchanging thoughts

Ruby On Rails

PHP

Postgres

Debian & Ubuntu
jQuery & CSS

Testing Private Methods With SimpleTest - Example

Here’s quick example how to test private class method with SimpleTest using RelectionClass (while you are reading about reflection class I will also point you directly to reflection method and what it’s all about).

Our class that we want to test with some private method:

sample_class.php
1
2
3
4
5
6
7
8
9
<?php
class SampleClass {

  private function myPrivateMethod($arg1) {
    return $arg1 == 7;
  }

}
?>

And here’s how you test that myPrivateMethod:

sample_class_spec.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
class SampleClassTest extends UnitTestCase {

  function testPrivateMethod() {
    $reflection_class = new ReflectionClass("SampleClass");
    $method = $reflection_class->getMethod("myPrivateMethod");
    $method->setAccessible(true);

    $sample_class = new SampleClass();

    $result = $method->invoke($sample_class, 7); # here you invoke method with you class object and pass arguments
    $this->assertEqual($result, true);

  }
}
?>

Comments