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?
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With