Search code examples
phpif-statementphpunittddfile-exists

How to make PHPUnit wait for condition test?


Every-time that run the test it fails at first run and pass at second run.

Here is the code:

 /** @test */
    public function some_function_test()
        {
            $file = file_exists($this->path.'file');

            if ($file) {
                echo "\n file exists! \n";
            }else{
                $this->createFile;
            }

         $this->assertEquals($file, true);

        }

when I delete the file and run the test again it fails. which tells me that the assertion is running before my if statement.

if the assertion is running first, can I make it wait for my condition test?


Solution

  • Your assertion will never run before if.

    Your test fails because in else branch you don't change $file after file is created with createFile, so in else branch $file is still false. I suppose you need to change $file to true:

    public function some_function_test()
    {
        $file = file_exists($this->path.'file');
    
        if ($file) {
            echo "\n file exists! \n";
        }else{
            $this->createFile();    // you're calling a method, aren't you?
            $file = true;
        }
    
        $this->assertEquals($file, true);
        // or simplier:
        // $this->assertTrue($file);
    }