3

I have this code:

public function testFoo() {
    $this->object = newBar();
}

But later, e.g., in method testAdd(), $this->object is null. testAdd executes after testFoo.

Why does this happen, and is there any setUp-like method for whole test case?

2 Answers 2

2

Every test method is executed on a new instance of the test case class. There is indeed a setup method that is called before each test, and it's called setUp.

public function setUp() {
    $this->object = newBar();
}

public function testFoo() {
    // use $this->object here
}

public function testBar() {
    // use $this->object here too, though it's a *different* instance of newBar
}

If you need to share state across all tests for a test case--often ill-advised--you can use the static setUpBeforeClass method.

public static function setUpBeforeClass() {
    self::$object = newBar();
}

public function testFoo() {
    // use self::$object here
}

public function testBar() {
    // use self::$object here too, same instance as above
}
Sign up to request clarification or add additional context in comments.

6 Comments

I solve it in the similar way: protected function setUp() { if (!self::$object) { self::$object = new Foo(); } }
@pinepain - That works of course, but using setUp to mimic setUpBeforeClass complicates the code unnecessarily.
Oh, i get it, thank you, i spent whole evening to find this method documentation.
No worries. While at first PHPUnit seems way more complicated than SimpleTest, it gets easier fairly quickly. It is patterned after JUnit and similar implementations so the knowledge will transfer, too.
I think that accessing in this way is not a good idea, in general. Probably the problem is in a wrong design. What do you think about Test Data Builders pattern to use in this situation?
|
1

I asked a question similar to this before here: Why are symfony DOMCrawler objects not properly passed between dependent phpunit tests?.

Basically, some sort of shutdown method is called between tests unless you explicitly make them dependent, which is not advised. One option is to override the setUp method if there's something you want for each test though.

1 Comment

I found that __constructor is called for every test method. Probably i have to read manual one more time, but anyway it's a strange behavior as for me (I migrated from SimpleTest).

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.