amir5's avatar
Level 7

Is there any way to use pest or phpunit assertion in application?

How can I sue pest or phpunit asserts inside of my application(not in test)? And when they fail, throw exception.

currently what I've tried:

expect(false)->toBeTrue(); // error: PHPUnit\TextUI\Configuration\Registry::get(): Return value must be of type PHPUnit\TextUI\Configuration\Configuration, null returned
Assert::isTrue(false); // phpunit: won't throw any exception
0 likes
11 replies
tisuchi's avatar

@amir5 What is the purpose of it?

BTW (without knowing the purpose), but YES, you can use it this way:

For PHP-UNIT.

use Exception;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\ExpectationFailedException;

try {
    Assert::assertTrue(false); // This will fail and throw an exception
} catch (ExpectationFailedException $e) {
    throw new Exception('Assertion failed: ' . $e->getMessage());
}

For PEST.


use Pest\Expectation;
use PHPUnit\Framework\ExpectationFailedException;

try {
    // Boot Pest expectation and use `expect()`
    expect(false)->toBeTrue(); // This will fail
} catch (ExpectationFailedException $e) {
    throw new Exception('Pest expectation failed: ' . $e->getMessage());
}
1 like
amir5's avatar
Level 7

@tisuchi both of them fail: PHPUnit\TextUI\Configuration\Registry::get(): Return value must be of type PHPUnit\TextUI\Configuration\Configuration, null returned

amir5's avatar
Level 7

@Snapey I know, but testing libraries provide more convenient methods for many type of assertions.

amir5's avatar
Level 7

@Snapey expect($test)->toBeIn(['test', 'foo', 'bar']); It's a little bit more readable.

Snapey's avatar

@amir5 why would you want to use this and then have to handle the exception, when you can do a simple array search

1 like
Tray2's avatar

That sound like a bad idea to me. Those tools should not be used for other things than testing. There is a reason for them to be require dev, and not require.

1 like

Please or to participate in this conversation.