Skip to main content

Functions That Throw

Many PHP functions refuse bad input by throwing an exception: on success they return the result, on failure they throw and never return at all.

A test for such a function must check both paths: the good input returns the right value without throwing, and the bad input actually throws — a function that silently accepts bad input is a bug too.


The Good Path

For a valid input the test simply calls the function and compares the value. No extra error check is needed: if the call throws unexpectedly, PHPUnit reports the exception and fails the test on its own.

Valid input, no exception

safeDivide(10, 2) must return 5.0 and throw nothing. One assertSame covers it — an unexpected exception would fail the test without any extra code.

Prompt
Write a PHPUnit test file with a safeDivide function that returns a float and throws an InvalidArgumentException when dividing by zero. Write a test for the good path: safeDivide(10, 2) must return 5.0, checked with a single assertSame — an unexpected exception would fail the test by itself. Show the phpunit output.
Output: PHP script
Valid input, no exception

The Bad Path

The other half of the contract: bad input must throw. The test declares the expectation before the call with expectException, then calls the function.

If the call throws the declared exception, the expectation counts as a passed assertion. If the call returns normally instead, the test fails — the function accepted input it should have rejected.

Bad input must throw

Dividing by zero has to fail. The test expects an InvalidArgumentException; safeDivide(10, 0) throws it, so the run reports OK (1 test, 1 assertion). A safeDivide that returned a value here would fail the test.

Prompt
Write a PHPUnit test for the bad path of safeDivide: calling it with divisor 0 must throw. Declare the expectation with expectException before the call. Show the phpunit output.
Output: PHP script
Bad input must throw

A Table with throws

Both paths fit into one data provider: give each row a throws field saying whether an exception is expected.

The test method checks that field first — for a throwing row it declares expectException, calls the function and returns. For the good rows it compares the value as usual.

Good and bad cases in one table

Four rows: three normal divisions and one division by zero with throws set to true. One test method covers the whole contract of the function — run with --testdox, all four cases pass.

Prompt
Write a data-provider PHPUnit test for safeDivide where each row has a name, the two inputs, the expected value and a throws flag. For throwing rows declare expectException and call the function; compare the value only for rows without an expected exception. Include three normal cases and one division by zero. Show the phpunit --testdox output.
Output: PHP script
Good and bad cases in one table