sub throws-like

Documentation for sub throws-like assembled from the following types:

module Test

From Test

(Test) sub throws-like

Defined as:

sub throws-like($code$ex_type$reason?*%matcher)

Marks a test as passed if the given $code throws the specific exception expected exception type $ex_type. The code $code may be specified as something Callable or as a string to be EVALed. The exception may be specified as a type object or as a string containing its type name.

If an exception was thrown, it will also try to match the matcher hash, where the key is the name of the method to be called on the exception, and the value is the value it should have to pass. For example:

sub frodo(Bool :$destroys-ring{
    fail "Oops. Frodo dies" unless $destroys-ring
throws-like { frodo }Exceptionmessage => /dies/;

The function accepts an optional description of the test as the third positional argument.

The routine makes Failures fatal. If you wish to avoid that, use no fatal pragma and ensure the tested code does not sink the possible Failures. If you wish to test that the code returns a Failure instead of throwing, use fails-like routine instead.

sub fails-not-throws { +"a" }
# test passes, even though it's just a Failure and would not always throw: 
throws-like { fails-not-throws }Exception;
# test detects nothing thrown, because our Failure wasn't sunk or made fatal: 
throws-like { no fatalmy $ = fails-not-throwsNil }Exception;

Please note that you can only use the string form (for EVAL) if you are not referencing any symbols in the surrounding scope. If you are, you should encapsulate your string with a block and an EVAL instead. For instance:

throws-like { EVAL q[ fac("foo") ] }X::TypeCheck::Argument;