Tutorial: Test-driven development
Whether you like to write your tests before writing production code, or like to create the tests afterwards, IntelliJ IDEA makes it easy to create and run unit tests. In this tutorial we’re going to show how to use IntelliJ IDEA to write tests first (Test Driven Development or TDD).
Launch IntelliJ IDEA.
If the Welcome screen opens, click New Project. Otherwise, go to File | New | Project in the main menu.
From the list on the left, select Java.
Name the new project, for example:
MoodAnalyser
and change its location if necessary.Select Gradle as a build tool and Groovy as a DSL.
From the JDK list, select the JDK that you want to use in your project.
If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory.
If you don't have the necessary JDK on your computer, select Download JDK.
Click Create.
IntelliJ IDEA creates a project with pre-configured structure and essential libraries. JUnit 5 will be added as a dependency to the build.gradle file.
Right-click the main | java folder in the Project tool window and select New | Package.
Name the new package
com.example.demo
and press Enter.
Given that we’re writing our tests first without necessarily having the code we’re testing available to us yet, we’ll create our first test via the project panel and place it in a package.
Right-click the test root folder and select New | Java Class.
In the popup that opens, name the new package and test class:
com.example.demo.MoodAnalyserTest
.Place the caret inside the curly braces in the class, press AltInsert.
Select Test Method from the menu to create a test method from the default template.
Name the method
testMoodAnalysis
, press Enter, and the caret will end up in the method body.You can alter the default test method template - for example, if you wish to change the start of the method name from
test
toshould
.
It may seem counter-intuitive to write test code for classes and methods that don’t exist, but IntelliJ IDEA makes this straightforward while keeping the compiler happy. IntelliJ IDEA can create classes and methods for you if they don’t already exist.
Type
new MoodAnalyser
, press AltEnter, and select Create class 'MoodAnalyser'.In the dialog that opens, select the
com.example.demo
package in the main | java folder and click OK.
As always, you can use IntelliJ IDEA’s refactoring tools to create variables to store results in, and IntelliJ IDEA will import the most appropriate classes for you if the correct libraries are on the classpath.
Switch back to the test class, place your cursor after
new MoodAnalyser
, type()
and press CtrlAlt0V to invoke the Extract/Introduce Variable refactoring.Name the new variable
moodAnalyser
.
tip
Place the caret at the test class or at the test subject in the source code and press CtrlShift0T to quickly navigate between them. Alternatively, use the Split Screen mode to see both files at the same time.
Continue writing the test body, including names of methods that you need that don’t exist.
In the test class, type the following statement:
moodAnalyser.analyseMood("This is a sad message");
analyseMood
will be marked as an unresolved reference.Place the caret at
analyseMood
, press AltEnter, and click Create method 'analyseMood' in 'MoodAnalyser'.Make sure the
MoodAnalyser
class looks as follows:public class MoodAnalyser { public String analyseMood(String message) { return null; } }
In the test class, place the caret at
analyseMood
, press CtrlAlt0V, and typemood
.
Open the build.gradle file, add the following dependency and click to import the changes:
dependencies { testImplementation( 'org.hamcrest:hamcrest-library:2.2' ) }
In MoodAnalyserTest, add the following statement:
assertThat(mood, CoreMatchers.is("SAD"));
Import the missing methods and classes by pressing AltEnter.
At this point, your test and production classes should look as follows:
package com.example.demo;
public class MoodAnalyser {
public String analyseMood(String message) {
return null;
}
}
package com.example.demo;
import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
public class MoodAnalyserTest {
@Test
void testMoodAnalysis() {
MoodAnalyser moodAnalyser = new MoodAnalyser();
String mood = moodAnalyser.analyseMood("This is a sad message");
assertThat(mood, CoreMatchers.is("SAD"));
}
}
When following a TDD approach, typically you go through a cycle of Red-Green-Refactor. You’ll run a test, see it fail (go red), implement the simplest code to make the test pass (go green), and then refactor the code so your test stays green and your code is sufficiently clean.
The first step in this cycle is to run the test and see it fail.
Given that we’ve used IntelliJ IDEA features to create the simplest empty implementation of the method we’re testing, we do not expect our test to pass.
From inside the test, press CtrlShiftF10 to run this individual test.
The results will be shown in the Run tool window. The test name will have an icon next to it — either red for an exception or yellow for an assertion that fails. For either type of failure, a message stating what went wrong is also shown.
The next step is to make the tests pass, which means implementing the simplest thing that works. Often with TDD, the simplest thing that works might be hard-coding your expected value. We will see later how iterating over this process will lead to more realistic production code.
In MoodAnalyser, replace
null
with theSAD
return value:return "SAD";
.Re-run the test, using ShiftF10 to re-run the last test.
See the test pass - the icon next to the test method should go green.
Developing code is an iterative process. When following a TDD-style approach, this is even more true. In order to drive out more complex behaviour, we add tests for other cases.
In your test class, use AltInsert again to create a new test method. Name it
HappyMoods
.Add the following code to your class.
@Test void HappyMoods() { MoodAnalyser moodAnalyser = new MoodAnalyser(); String mood = moodAnalyser.analyseMood("This is a happy message"); assertThat(mood, CoreMatchers.is("HAPPY")); }
Run this second test case by pressing AltShift0R, you will see that it fails.
Change the code in the method being tested to make this test pass:
package com.example.demo; public class MoodAnalyser { public String analyseMood(String message) { if (message.contains(("sad"))) { return "SAD"; } else { return "HAPPY"; } } }
Re-run both the tests by pressing CtrlShiftF10 inside the test class, not inside a single method, and see that both tests now pass.
Writing your first test in a test-first style takes a small amount of setup – creating the test class, creating the test methods, and then creating empty implementations of the code that will eventually become production code. IntelliJ IDEA automates a lot of this initial setup.
As you iterate through the process, creating tests and then making the changes required to get those tests to pass, you build up a comprehensive suite of tests for your required functionality, and the simplest solution that will meet these requirements.
Thanks for your feedback!