1

I am using JUnit 5 library and I try to use assertThrows and get the exception thrown in order to get the message of the exception. I have such piece of code:

import org.junit.jupiter.api.Assertions;
//import org.junit.Assert;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;

import static org.junit.jupiter.api.Assertions.*;

public class Tests {
    private static void execute() throws Exception {
        ArrayList<String> filter = ListString.filter(new ArrayList<String>(Arrays.asList("1", "2", "3")), "4");
    }

    @Test
    public void listStringTest() {
        // This part doesn't work 
        Throwable throwable = Assertions.assertThrows(Exception.class, Tests::execute);
        assertEquals("Exception texnt", throwable.getMessage());
    }
}

I get the following message:

enter image description here

But the documentation says that assert throws returns T extends Throwable, not void:

enter image description here

Where did I make a mistake?

ibodi
  • 1,543
  • 3
  • 21
  • 40
  • Either the documentation is wrong, or more likely you're not using the version you're thinking of. If you ctrl-click on the `assertThrows`, where do you end up? – Kayaman Sep 18 '19 at 08:40

2 Answers2

1

It could be possible that you have a really old version of JUnit Jupiter in your classpath.

The milestone release 5.0.0-M3 (November 2016, release notes) added the return type to assertThrows. The version in your classpath seems to be older than that.

Make sure that you use a recent version of JUnit.

Roland Weisleder
  • 9,668
  • 7
  • 37
  • 59
0

I found the solution. It turns out that I used old version of JUNIT Jupiter.

I had such dependencies in my build.gradle file:

dependencies {
    testCompile 'org.junit.jupiter:junit-jupiter-api:5.0.0-M2'
}

When I updated them to the newest version:

dependencies {
     testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.5.2'
}

it worked as expected.

ibodi
  • 1,543
  • 3
  • 21
  • 40