如何为phpunit断言设置多个可接受的值

问题描述 投票:0回答:3

我在 Laravel 中使用 Phpunit,我的 Api 有多个可接受的响应。我有两种情况的问题:

1-响应结构可以是这两个中的一个

$response->assertJsonStructure(['cities'=>[]]);  

or

$response->assertJsonStructure(['cities'=>[['id','name']]])

2-响应状态可以是200或302

$response->assertStatus(200);

or

$response->assertStatus(302);

但是我找不到任何方法来“或”这两个条件。

我正在寻找这样的东西:

$response->assertOr(
    $response->assertStatus(200),
    $response->assertStatus(302)
);
php laravel phpunit
3个回答
6
投票

for #1 如果您认为该值可能为空,只需将键与

assertArrayHasKey()

匹配即可
$response->assertArrayHasKey('cities', $response->getContent()); 

对于#2您可以使用

assertContains()
喜欢


 $response->assertContains($response->getStatusCode(), array(200,302));

在这里您可以找到更多信息。 https://phpunit.readthedocs.io/en/7.4/assertions.html#assertcontains


1
投票

对于 2° 的情况,您可以使用类似

if($response->getStatusCode() == 410) {
  $response->assertStatus(410);
} else {
  $response->assertStatus(200);
}


0
投票

我将其添加到我的基础

TestCase
类中:

/**
 * Assert that at least one of the `callable`s pass (short-circuiting)
 * @param array<callable> $callables
 * @return void
 */
public function assertOr(array $callables, int $minimum = 1): void {
    $this->assertGreaterThanOrEqual(1, $minimum);
    $passCount = 0;

    foreach ($callables as $callable) {
        $passes = true;
        try {
            $callable();
        } catch (ExpectationFailedException $e) {
            $passes = false;
        }
        $passCount += (int) $passes;
        if ($passCount >= $minimum) {
            break;
        }
    }

    $this->assertGreaterThanOrEqual($minimum, $passCount);
}
© www.soinside.com 2019 - 2024. All rights reserved.