Support for JUnit 5 M4 in IntelliJ IDEA 2017.2

IntelliJ IDEA provides support for the upcoming JUnit 5 release. JUnit has pretty much been the standard for Java unit testing for years, and the latest version brings the library right up to date, making use of Java 8 features and bringing in ways of testing that are familiar if you’ve been using other frameworks like Spock.  IntelliJ IDEA 2017.2 adds support for some of these features, to make the experience of testing code as painless and quick as possible.

JUnit 5 supports parameterized tests. These tests let you use the same basic structure of a test with a number of different inputs. This reduces duplication in your test code and also lets you easily add new cases without having to create entire new tests.

IntelliJ IDEA helps you with parameterized tests in a number of different ways,  Firstly, it reports “suspicious” use of both @Test and @ParameterizedTest annotations – you only need one of these in order to declare the method is a test.

Suspicious Annotations

If you press Alt + Enter on the highlighted @Test annotation, IntelliJ IDEA suggests removing this unnecessary annotation.

Remove Test Annotation suggestion

If you’re using the @ParameterizedTest annotation, you need to supply a source for the parameters, otherwise there are no tests to run.  IntelliJ IDEA warns you if you use the @ParameterizedTest annotation without an associated source (annotations like @MethodSource, @ValueSource etc.)

No sources supplied

If you’re using a source annotation, but it doesn’t match the expectations set by the  test method, you’ll also get a warning about this.  For example, if you use a @ValueSource that defines a series of ints as the input, but your test method takes a String parameter, IntelliJ IDEA will warn you that these types don’t match

Incorrect parameter types

Using a @MethodSource lets you choose a method that returns a Stream of values to use for parameters, and IntelliJ IDEA offers suggestions of suitable methods

Code completion for MethodSource

If you select a method that does not provide the right values for the test method’s arguments, you’ll get a warning about this as well. Here, we’ve given @MethodSource a method that returns a Stream of Strings, but because our test takes more than one argument we should have chosen a method that returns a Stream of Arguments.

Incorrect method source type

You’ll notice as well that when you provide a method to @MethodValue, this method is not marked as unused because IntelliJ IDEA recognises it’s used in the annotation.

No unused method

In addition to this support for parameterized tests, you also get warnings for using the @Test annotation with @RepeatedTest.

Help for repeated tests

IntelliJ IDEA 2017.2 makes it simple to use all the features in JUnit 5, so that it’s easier and quicker to write effective tests.

image description