【问题标题】:How to make PHPUnit wait for condition test?如何让 PHPUnit 等待条件测试?
【发布时间】:2018-08-28 20:41:58
【问题描述】:

每次运行测试时,它都会在第一次运行时失败并在第二次运行时通过。

代码如下:

 /** @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);

        }

当我删除文件并再次运行测试时,它失败了。 这告诉我断言在我的 if 语句之前运行。

如果断言首先运行,我可以让它等待我的条件测试吗?

【问题讨论】:

  • Assertion 不能在 if 之前运行。如果您没有文件-您使用createFile 创建它,这是一种方法吗?那么它应该是createFile(),但$file 变量在else 分支中没有变化。这就是你的测试失败的原因。
  • @u_mulder 但是 $file 没有改变也没关系,因为它有一个完整的路径和文件名!如果文件存在,断言应该返回真!但似乎我在创建文件之前进行了断言检查。为什么如果我第二次运行测试总是通过?
  • 因为第二次运行测试文件是创建的

标签: php if-statement phpunit tdd file-exists


【解决方案1】:

您的断言将永远if 之前运行。

您的测试失败,因为在else 分支中,您在使用createFile 创建文件后没有更改$file,因此在else 分支中$file 仍然是false。我想您需要将$file 更改为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);
}

【讨论】:

  • 是的,我在 else 语句之后调用了一个方法,但是一旦这个方法创建了文件,断言应该看到并返回 true!或者有什么我没有抓住的东西。 else 语句是否将 $file 更改为 false?如果有怎么办?
  • 你明白断言检查变量的值吗?它检查变量$file 的值。如果文件不存在,$file 的值为 false。创建文件时 - 您只需创建文件,不会更改 $file 的值。所以它仍然是false。清楚了吗?
  • "是 else 语句将 $file 更改为 false 吗?" -- else 分支被执行 因为 $file 是@987654336 @.
  • @u_mulder 谢谢你现在一切正常。我仍然是专门编程 TDD 的新手。你个摇滚!
猜你喜欢
  • 2013-04-03
  • 1970-01-01
  • 1970-01-01
  • 2019-10-31
  • 1970-01-01
  • 2013-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多