Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access object initialised in another PHPUnit test

Tags:

php

phpunit

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?

like image 932
pinepain Avatar asked Mar 05 '26 00:03

pinepain


2 Answers

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
}
like image 169
David Harkness Avatar answered Mar 07 '26 14:03

David Harkness


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.

like image 20
Squazic Avatar answered Mar 07 '26 12:03

Squazic