lithium\test\Unit::assertException()

public method

Assert that the code passed in a closure throws an exception or raises a PHP error. The first argument to this method specifies which class name or message the exception must have in order to make the assertion successful.

Parameters

  • mixed $expected

    A string indicating what the error text is expected to be. This can be an exact string, a /-delimited regular expression, or true, indicating that any error text is acceptable.

  • \Closure $closure

    A closure containing the code that should throw the exception.

  • string $message

Returns

boolean

true if the assertion succeeded, false otherwise.

Source

	public function assertException($expected, $closure, $message = '{:message}') {
		$result = null;

		try {
			$closure();
			$message = sprintf('An exception "%s" was expected but not thrown.', $expected);
			return $this->assert(false, $message, compact('expected', 'result'));
		} catch (Throwable $e) {
			// fallthrough
		}
		$class = get_class($e);
		$eMessage = $e->getMessage();

		if (get_class($e) === $expected) {
			$result = $class;
			return $this->assert(true, $message, compact('expected', 'result'));
		}
		if ($eMessage === $expected) {
			$result = $eMessage;
			return $this->assert(true, $message, compact('expected', 'result'));
		}
		if (Validator::isRegex($expected) && preg_match($expected, $eMessage)) {
			$result = $eMessage;
			return $this->assert(true, $message, compact('expected', 'result'));
		}

		$message = sprintf(
			'Exception "%s" was expected. Exception "%s" with message "%s" was thrown instead.',
			$expected, get_class($e), $eMessage
		);
		return $this->assert(false, $message);
	}