1
class myclass {

    private $myemail = '';       
    private $myPrefix = '';


    /**
     * @return string
     */
    public function getmyPrefix()
    {
        return $this->myPrefix;
    }

    /**
     * @return string
     */
    public function getmyEmail()
    {
        return $this->myemail;
    }

    /**
     * @param string $email
     */
    public function setmyEmail($email)
    {
        $this->myemail = $email;
    }
}

I want to write a php unit tests to test the private variables in this class but I am not sure how to test the variable $myPrefix because it does not have a setter ? Do I need to create a mock class ?

Thanks

Farid Movsumov
  • 12,350
  • 8
  • 71
  • 97
Jallal
  • 101
  • 1
  • 2
  • 9
  • 2
    If you don't have a setter. How do you set `$myprefix` anyway? it is nothing to be tested because it's never going to be changed. – barbarity Mar 09 '15 at 16:54
  • 1
    what do you mean by "it does not have a setter"? you can set that variable either with a __construct() or through a custom function like "setmyEmail". – briosheje Mar 09 '15 at 16:55
  • @edorian had a very good answer to this question [here](http://stackoverflow.com/a/8929561/870835) – nickell Mar 09 '15 at 16:56
  • 1
    @barbarity is right. There's no setter and no constructor, so there's nothing to test. It failed the test before you came up with one. – developerwjk Mar 09 '15 at 17:01

1 Answers1

0

You can do a simple test to ensure the initial value is null by simply testing the return from the class. Then use your Setter or __construct() to populate the field, and test the return from the getter again.

Optionally, and you do not need to go to this level of testing internal private fields as they should not change from outside the module, you can use Reflection.

I have some library classes that do things based on inputs, and I do use reflection to test the odd setting to be updated/set as I would expect for the function/method to work properly. This is done sparingly as the private values should not be changed external to the code library, but the test is for developer documentation purposes, and to ensure the basic functionality and assumptions in the code are not broken.

From the PHP Manual

    $class = new ReflectionClass('myClass');
    $property = $class->getProperty('myPrefix');
    $this->assertEquals("Something from your setter", $property);

I would only use this to ensure that the set method (or constructor) is directly setting the field, not manipulating it in any way. However, with a get method, this is not needed since the get..() can test this. I only added the quick reference code to show you could test a value that did not have a get method.

Steven Scott
  • 10,234
  • 9
  • 69
  • 117