Skip to the content.

Callable API

up

Here are the examples of how you can use the should function with exceptions.

Summary

Examples

Throw exception

You can check if some code throws or not Exceptions. The throwException template will return a ThrowableProxy which for convience it has all the Throwable properties. A simple way of checking an exception message is:

    ({
        throw new CustomException("test");
    }).should.throwException!CustomException.msg.should.equal("test");

or

    void myFunction() {
        throw new CustomException("test");
    }

    /// This way of testing exceptions does not work with
    /// functions that return arrays or ranges
    myFunction.should.throwException!CustomException.msg.should.equal("test");

The ThrowableProxy it also have a withMessage method that returns a new should structure, initialized with the exception message:

    ({
        throw new CustomException("test");
    }).should.throwException!CustomException.withMessage.equal("test");

or

    void myFunction() {
        throw new CustomException("test");
    }

    myFunction.should.throwException!CustomException.withMessage.equal("test");

Success expectations

    ({
        throw new CustomException("test");
    }).should.throwException!CustomException;

    ({ }).should.not.throwException!CustomException;

Failing expectations

    ({
        throw new Exception("test");
    }).should.not.throwException!CustomException;

    ({ }).should.throwException!CustomException;

Throw any exception

The throwAnyException assert is an alias for throwException!Exception

Success expectations

    ({
        throw new Exception("test");
    }).should.throwAnyException;

    ({ }).should.not.throwAnyException;

Failing expectations

    ({
        throw new Exception("test");
    }).should.not.throwAnyException;

    ({ }).should.throwAnyException;

Throw something

The throwSomething assert is an alias for throwException!Throwable

  ({
    assert(false, "test");
  }).should.throwSomething.withMessage.equal("test");

Execution time

Success expectations

    ({ }).should.haveExecutionTime.lessThan(1.msecs);

Failing expectations

    ({
      Thread.sleep(2.msecs);
    }).should.haveExecutionTime.lessThan(1.msecs);

Be null

Success expectations

    void delegate() action;
    action.should.beNull;

    ({ }).should.not.beNull;

Failing expectations

    void delegate() action;
    action.should.not.beNull;

    ({ }).should.beNull;