0

I'm tring to do a phpUnit test to a function A that calls another function B inside it, how can I replace the return of the function B to continue succesfully my test

public function A($parameter = null){
// do something
$response_B = $this->B();
// continue with the function A
}

Note: the function B make a query in SQL to a database. In my test I don't want to do any query, simply I want to pre define a result of the function B. I have tried with Mocks and Stubs, but realy I dont understand it completly. Please sorry with my English

  • 1
    What do you mean by `replace the return of the function B`? Try adding sample code to help us get a better understanding – Antony Jan 25 '17 at 14:28
  • Can you upload your code please? – Svekke Jan 25 '17 at 14:28
  • You can use fixtures or mock, but without knowing, what your really want to do, it is hard to help you – Oliver Jan 25 '17 at 14:38
  • `I have tried with Mocks and Stubs` Then it would be great if you show your tryouts here. How to mock functions is also good docmented at phpunit and look here: http://stackoverflow.com/questions/2357001/phpunit-mock-objects-and-static-methods#2357141 or http://stackoverflow.com/questions/18482362/phpunit-how-to-mock-a-function-on-a-class – JustOnUnderMillions Jan 25 '17 at 14:45

2 Answers2

0

Example of function:

function pass(){
 $test = check(3);
 return $test; //returns true when 3 is parameter used to call function check()
}

function check($int) {
 if ($int == 3) {
 return true;
 } else {
 return false;
}
Svekke
  • 1,470
  • 1
  • 12
  • 20
0

so what you want, called "Mocking" and this will not work with a simple function.

to make it simple.(code is not tested)

class MySpecialClass
{
 public function doSomeSpecialThings(){
  $response = $this->doFancySQL();
  return $response;
 }
}

so if you want to manipulate the method call, you have to extract it to an external class and inject it

class MySpecialClass
{
  public function setFancySqlInterface(FancySqlInterface $fancySqlInterface){
 $this->fancySqlInterface = $fancySqlInterface;
 }
 public function doSomeSpecialThings(){
  $response = $this->fancySqlInterface->doFancySQL();
  return $response;
 }
}

with this, now you can use the method setFancySqlInterface in your test with a fake class which returns a specific response.

you can either create a fake class or use a "Mocking Framework" for this task

as an example, you can see here

https://github.com/BlackScorp/guestbook/blob/master/tests/UseCase/ListEntriesTest.php#L35 that i created fake entities and added them to an Fake repository https://github.com/BlackScorp/guestbook/blob/master/tests/UseCase/ListEntriesTest.php#L70

hope you understand what i mean :D

Vitalij Mik
  • 542
  • 3
  • 6