Search code examples
phpphpunittdd

How to get result from expectException and passed test in PHPUnit?


I have an app in docker with PHP 7.2 and I must rebuild it using TDD.

I have this method in Cart Class:

public function getItem($index)
{
    if (!isset($this->items[$index])) {
        throw new \Exception('Item with index('.$index.') not exists', '404');
    }
    $this->chosenItem = $index;
    
    return $this;
}

And another in Test Class with test:

public function itThrowsExceptionWhileGettingNonExistentItem(int $index): void
{
    $product = $this->buildTestProduct(1, 15000);

    $cart = new Cart();
    $cart->addProduct($product, 1);
    $cart->getItem($index);

    $this->expectException(\Exception::class);
}

And when I run phpunit I have this message in terminal:

There were 4 errors:

1) Recruitment\Tests\Cart\CartTest::itThrowsExceptionWhileGettingNonExistentItem with data set #0 (-9223372036854775807-1)
Exception: Item with index(-9223372036854775808) not exists
src\Cart\Cart.php:88
tests\Cart\CartTest.php:102

And I don't have a good result marked in the final phpunit.txt report

 [ ] It throws exception while getting non existent item with data set #0

What am I doing wrong? The thread is thrown and displayed, but the PHPUnit test still failed?


Solution

  • Correct code for your test is:

    public function itThrowsExceptionWhileGettingNonExistentItem(int $index): void
    {
        $this->expectException(\Exception::class);
    
        $product = $this->buildTestProduct(1, 15000);
        $cart = new Cart();
        $cart->addProduct($product, 1);
        $cart->getItem($index);
    }
    

    You must first define that exception will happen, and after that run the code which will throw this exception.