22

I'm writing functional tests for a SOA system so need to test a backend subsystem from the frontend.

It's a standard CRUD system. I have a test that tests I can create an object, and it returns me the ID of the new object. In subsequent tests I want to edit and then delete this object, but phpunit seems to be re-instantiating the test class each time, so I lose my instance variables.

How can I achieve this? Running functional tests on each server in the architecture isn't an option.

2
  • 3
    One thing to keep in mind is that PHPUnit creates a new instance of your test case for each test method before executing any tests. Commented Jul 18, 2011 at 18:15
  • 4
    One thing to keep in mind is that PHPUnit has bad design... Commented Jul 30, 2013 at 15:08

4 Answers 4

41

One way to pass stuff between tests is to use the @depends annotation

public function testCreate() {
    //...
    return $id;
}

/**
 * @depends testCreate
 */
public function testDelete($id) {
    // use $id
}

if you do it like that the "delete" test will be skipped if the creation doesn't work.

So you will only get one error if the service doesn't work at all instead of many failing tests.


If you don't want to do that or that doesn't match your case for whatever reason static class variables can also be an option, but you should be really sure that you know you absolutely need them :)

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

1 Comment

I have exactly the same method names that I was looking solution for :D
5

Since you want to run each testcase once, you can store the instance variables on class level for example in static variables, or in an external singleton/global store uses get_class($testCase) for keys...

Comments

0

I guess I'll just run the 'create' test before I run the 'edit' or 'delete', and set the instance variable accordingly.

Comments

0

Use setUp() method of TestCase class.

protected function setUp(): void
{
    parent::setUp();
    //init something
}

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.