Imanol Imanol - 1 year ago 138
Java Question

How to test that an expected exception is being thrown using google-truth?

I just want to test if an Exception with a given message is being thrown using google-truth.

Is quite easy to do that using junit using

, but I'm unable to figure out how to do that with truth. There are no samples around ThrowableSubject.

Should I stick with plain
for these kind of tests?

Answer Source

There is currently no built-in way to verify an expected Exception with google-truth. You can do one of the following:

I believe google-truth does not have any similar functionality because it supports Java 1.6.

import org.junit.Test;

import java.util.concurrent.Callable;

import static;

public class MathTest {
    public void addExact_throws_ArithmeticException_upon_overflow() {
            .that(() -> Math.addExact(Integer.MAX_VALUE, 1))

    static <T> SubjectFactory<CallableSubject<T>, Callable<T>> callable(String displaySubject) {
        return new SubjectFactory<CallableSubject<T>, Callable<T>>() {
            @Override public CallableSubject<T> getSubject(FailureStrategy fs, Callable<T> that) {
                return new CallableSubject<>(fs, that, displaySubject);

    static class CallableSubject<T> extends Subject<CallableSubject<T>, Callable<T>> {
        private final String displaySubject;

        CallableSubject(FailureStrategy failureStrategy, Callable<T> callable, String displaySubject) {
            super(failureStrategy, callable);
            this.displaySubject = displaySubject;

        @Override protected String getDisplaySubject() {
            return displaySubject;

        void willThrow(Class<?> clazz) {
            try {
                fail("throws a", clazz.getName());
            } catch (Exception e) {
                if (!clazz.isInstance(e)) {
                    failWithBadResults("throws a", clazz.getName(), "throws a", e.getClass().getName());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download