5

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?

1
  • 1
    Whether or not there is a "better approach" depends on what you are actually trying to achieve. Commented May 18, 2011 at 1:48

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

A nice shortcut is to use list($obj1, $obj2) = $myClasses;
2

This would make more sense, I guess?

return array(
    'obj1' => new Class1( ),
    'obj2' => new Class2( )
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.