0

My question is. I have a class i want to test only thing the function i want to test is calling a private function in the class i want to test. The private function calls another class function.

I want to mock the private function so i can return value to the public functions that calls the private. I try it by creating a new class with the same function but with the value i want the function to return.

Here is my code

//function i want to test
public function checksomedata($objectID){
        $config = $this->theprivatefunction($objectID,'id');
        return $config;
    }

the private function i want to mock

private function theprivatefunction($objectID,'id'){
//do some code here. nothing special
//return the value here
}

here is my test

public function testCheckObjectAcces() {
        $objectID = '12';
      $this->testclass->checksomedata($objectID);
    }

here is my class i want to call to return some value.

public function theprivatefunction(){
        $result = "THIS VALUE NEEDS TO BE RETURNED";
        return $result;
    }

and my setUP where i try to mock the priavte function

$this->mockextended = new \stdClass();
        $this->mockextended = new MOCKEXTENDEDCLASSES();
        $this->testclass->theprivatefunction() = $this->mockextended->theprivatefunction();

In my setUp i want the code to think $this->testclass->theprivatefunction() is $this->mockextended->theprivatefunction();

So when a function is calling the private function it needs to be redirected to $this->mockextended->theprivatefunction();

Wim Pruiksma
  • 588
  • 5
  • 19
  • 2
    It's not possible to mock a private method using PHPUnit. https://stackoverflow.com/questions/5937845/mock-private-method-with-phpunit might give you some ideas about how you can approach this problem. – StuBez Oct 30 '15 at 09:17

1 Answers1

3

There are two approaches to this problem:

  1. You unit test the private method as part of the call to the public method. Your goal when unit testing is to test the class's public API. You test the private method through the public API, so should be testing the return value including the value returned from the private method. If the private method relies on some external state, then you make sure that state is set up (and torn down) at the beginning and end of the test, respectively.
  2. Sometimes, the private method is question simply isn't testable directly. As an example, I recently had an instance where the method I wrote was reading from stdin. As far as I'm aware, you can't assign a value to stdin in your tests, so I had to split off the read to stdin into a separate method. Then, I created a test stub, which overrode the parent method to return a pre-defined value. This gives you control over the private method that you wouldn't have normally.
mAAdhaTTah
  • 400
  • 1
  • 12