Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

phpunit - return two objects to next test case

Tags:

php

phpunit

In some places, my phpunit methods have dependency on two classes so I have decided to write a dedicate method which will create an instance of these two classes(which are related to each other) and will pass them to all phpunit methods. I want to do something like below.

public function testGetInstance()  
{  
    $obj1 = new Class1();  
    $obj2 = new Class2();  
    return $obj1, $obj2;  //can i use list  ?  
}    

/**  
*@depends testGetInstance()  
*/  
public function testBothFeatures(Class1 $obj1, Class2 $obj2) //how to pass 2 instances?      
{  
    //Do all operation related to $obj1 and $obj2  
}

How to achieve above case? Is there a better approach for same?

like image 904
CM. Avatar asked May 17 '11 11:05

CM.


2 Answers

The short answer:

@depends only works for one argument so you have to:

return array($obj1, $obj2);

public function testBothFeatures(array $myClasses) {
    $obj1 = $myClasses[0];
    $obj2 = $myClasses[1];
}

Longer answer:

What are you doing there? Are you using one PHPUnit Test Case to test TWO real classes?

If so thats something you should usually avoid. The only exception is that you might be doing an "integration" test that makes sure bigger parts of your code work together, but you should only do that once you have a unit test for every class.

You want to make sure your classes work independed of other parts of your application so you can easily spot what exactly you broke when you change something.

If you have a class that depends on another class then mock out the second class and use that fake object to make sure your "class under test" works correctly.

like image 115
edorian Avatar answered Nov 03 '22 05:11

edorian


This would make more sense, I guess?

return array(
    'obj1' => new Class1( ),
    'obj2' => new Class2( )
);
like image 40
Berry Langerak Avatar answered Nov 03 '22 04:11

Berry Langerak