【问题标题】:Continue test after expect exception phpunit期待异常phpunit后继续测试
【发布时间】:2020-01-25 22:31:07
【问题描述】:

我有代码。

        try {
            $this->entityManager->beginTransaction();

            $this->repo->remove($something);
            $this->repoTwo->delete($something);

            $this->entityManager->commit();
        } catch (Exception $e) {
            $this->entityManager->rollback();

            throw new Exception($e->getMessage(), 0, $e);
        }

现在,我想测试一下,如果数据库中仍有记录,发生异常后,我该怎么做,如果在预期异常后测试无法工作?

    $this->expectException(Exception::class);
    $this->expectExceptionMessage('xxxx');

    app(Command::class)->handle();

    $this->seeInDatabase($table, [
        'id' => $media->id(),
    ]);

我该怎么做?谢谢。

【问题讨论】:

  • 你不需要检查这个。你的类应该模拟所有依赖项,所以你可以检查 rollback 是否被调用。
  • @freeek 但是,如果我尝试模拟 entityManager 并尝试检查是否调用了回滚,无论如何我应该这样做,在我调用我的函数之后,但在 pp(MediaCleanupCommand::class)->handle(); 之后没有任何效果(也是 die() ;),
  • 是的,但是你应该在handle() 之前模拟,这样就可以了。之后不需要任何代码。
  • @freeek 谢谢,像这样工作,有没有机会,我可以测试,数据库上的记录真的存在吗?
  • 从我的角度来看,单元测试不需要这个。如果您要对其进行端到端测试,那将是有道理的。您检查您的方法是否按设计执行:因此事务被回滚。

标签: php exception transactions phpunit


【解决方案1】:

通常您可以创建两个测试。一个测试异常被抛出,一个 depends 在第一次测试和测试记录仍然存在,但在这种情况下,数据库将在每次测试之前重置,包括测试依赖项,因此它不会像您预期的那样工作.

但是你仍然可以做两个测试并且让一个依赖于另一个,但是你需要在两个测试中重新运行相同的代码(因为数据库会在测试之间被重置)。在这种情况下,“依赖”只是记录一个测试与另一个测试相关联。

public function testOne()
{
    $this->expectException(Exception::class);
    $this->expectExceptionMessage('xxxx');

    app(Command::class)->handle();
}

/**
 * @depends testOne
 */
public function testTwo($arg)
{
    app(Command::class)->handle();

    $this->seeInDatabase($table, [
        'id' => $media->id(),
    ]);
}

如果您真的想对其进行端到端测试,并在同一个测试中进行断言,那么您可以使用try ... catch 块并按程序进行测试。

public function testException()
{
    try {
        app(Command::class)->handle();
    } catch (\Exception $e) {
        // Make sure you catch the specific exception that you expect to be
        // thrown, (e.g. the exception you would normally specify in the
        // expectException method: $this->expectException(Exception::class);

        // Assert the exception message.
        $this->assertEquals('xxxx', $e->getMessage());

        // Assert database still contains record.
        $this->seeInDatabase($table, [
            'id' => $media->id(),
        ]);

        return;
    }

    // If the expected exception above was not caught then fail the test.
    $this->fail('optional failure message');
}

【讨论】:

    猜你喜欢
    • 2013-01-11
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 2015-10-17
    • 2016-04-27
    • 1970-01-01
    相关资源
    最近更新 更多