What happens to objects passed between dependent PHPUnit tests?

Mock objects in PHPUnit are attached to the test instance for which they are created, and this by definition means a single test method. The reason for this is that PHPUnit allows you to specify expectations on a mock that must be satisfied during a test. To do this it asserts those expectations once the method terminates successfully. If the mock lived across tests, expectations wouldn't work.

The problem is that this doesn't support stub objects: mocks that contain only canned actions to be taken in response to methods and inputs. Stubs do not validate that their methods are called as full mocks can. Perhaps PHPUnit could benefit from the ability to create stubs in setUpBeforeClass() that are not tied to the test instance.

Your other option is to use an external mock object library such as Mockery or Phake.

Edit: After looking over your sample code again, I wonder why you are surprised by this behavior. As Shaunak wrote, setUp() is called on a new instance before each test method is executed. Thus, each instance receives a new mock stdClass. If you want only one test method to receive an expectation, add it inside the test method itself. You can still create the mock object in setUp() with any behavior that should be common to all test methods.


I am not a php guy ,so correct me if I am wrong, but the all unit tests are designed to run in following sequence,

Setup --> test function --> destroy.

so setup and destroy function is called each time before executing any test function. This is done on purpose to preserve the purpose of unit testing.

If you want to have dependent unit test cases then you have to code them, that way instead of depending on global variables to do that (this defeats the purpose of unit tests!). If there are is a test case 'A' that depends on some function, call that function from 'A' and then assert the values.