Unit testing java intellij

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).

Create a project

Create new project

  1. Launch IntelliJ IDEA. If the Welcome screen opens, click New Project . Otherwise, from the main menu, select File | New | Project .
  2. From the list on the left, select New Project .
  3. Name the new project, for example: MoodAnalyser and change its location if necessary.
  4. Select Java as the language for this project.
  5. Select Gradle as a build tool and Groovy as a DSL.
  6. 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 .
  7. 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.

Create a new package

  1. Right-click the main | java folder in the Project tool window and select New | Package .
  2. Name the new package com.example.demo and press Enter .

Write the test body

Create your first test

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.

Test class created

  1. 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 .
  2. Place the caret inside the curly braces in the class, press Alt+Insert .
  3. Select Test Method from the menu to create a test method from the default template. Name the method testMoodAnalysis , press Enter , and the cursor will end up in the method body.

Create a new class from the test

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.

  1. Type new MoodAnalyser , press Alt+Enter , and select Create class ‘MoodAnalyser’ . Creating a new class from the test
  2. In the dialog that opens, select the com.example.demo package in the main | java folder and click OK . Selecting a destination package

Create variables

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.

  1. Switch back to the test class, type () and press Ctrl+Alt+V to invoke the Extract/Introduce Variable refactoring.
  2. Name the new variable moodAnalyser .

Place the caret at the test class or at the test subject in the source code and press Ctrl+Shift+T to quickly navigate between them. Alternatively, use the Split Screen mode to see both files at the same time.

Complete the test body

Continue writing the test body, including names of methods that you need that don’t exist.

    In the test class, type the following statement:

Introducing variable

  • In the test class, place the caret at analyseMood , press Ctrl+Alt+V , and type mood .
  • Add an assertion statement

    Code

    At this point, your test and production classes should look as follows:

    Run the tests

    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.

    Running the test

    • From inside the test, press Ctrl+Shift+F10 to run this individual test. The results will be shown in the run dialog. 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.

    Implement the code

    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.

    Fix the test

    Rerunning tests

    1. In MoodAnalyser , replace null with the SAD return value: return «SAD»; .
    2. Re-run the test, using Shift+F10 to re-run the last test. See the test pass — the icon next to the test method should go green.

    Iterate

    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.

    Add the second test case

    1. In your test class, use Alt+Insert again to create a new test method. Name it HappyMoods .
    2. Add the following code to your class. Use refactoring tools to add the variable.

    Fix the second test

    The second test passes

  • Re-run both the tests by pressing Ctrl+Shift+F10 inside the test class, not inside a single method, and see that both tests now pass.
  • Summary

    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.

    Источник

    JUnit 5

    In this tutorial, you will learn how to set up JUnit for your projects, create tests, and run them to see if your code is operating correctly. It contains just the basic steps to get you started.

    If you want to know more about JUnit, refer to the official documentation. To learn more about testing features of IntelliJ IDEA, refer to other topics in this section.

    You can choose to follow the tutorial using either Maven or Gradle.

    Create a project

    1. From the main menu, select File | New | Project .
    2. Select New Project . Specify the name for the project, for example, junit-tutorial .
    3. Select Maven as a build tool. In Language , select Java .
    4. 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 .
    5. Click Create .

    For more information on working with Maven projects, refer to Maven.

    Add dependencies

    For our project to use JUnit features, we need to add JUnit as a dependency.

    The Load Maven Changes button

    1. Open pom.xml in the root directory of your project. To quickly navigate to a file, press Ctrl+Shift+N and enter its name.
    2. In pom.xml , press Alt+Insert , select Add dependency .
    3. In the tool window that opens, type org.junit.jupiter:junit-jupiter in the search field. Locate the necessary dependency in the search results and click Add next to it.
    4. Now we need to apply the changes in the build script. Press Ctrl+Shift+O or click Load Maven Changes in the notification that appears in the top-right corner of the editor.

    Create a project

    1. From the main menu, select File | New | Project .
    2. Select New Project . Specify the name for the project, for example, junit-tutorial .
    3. Select Gradle as a build tool. In Language , select Java .
    4. 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 .
    5. Click Create .

    For more information on working with Gradle projects, refer to Gradle.

    Add dependencies

    For our project to use JUnit features, we need to add JUnit as a dependency.

    The Load Gradle Changes button

    1. Open build.gradle in the root directory of your project. To quickly navigate to a file, press Ctrl+Shift+N and enter its name.
    2. In build.gradle , press Alt+Insert , select Add dependency .
    3. In the tool window that opens, type org.junit.jupiter:junit-jupiter in the search field. Locate the necessary dependency in the search results and click Add next to it.
    4. Now we need to apply the changes in the build script. Press Ctrl+Shift+O or click Load Gradle Changes in the notification that appears in the top-right corner of the editor.

    Create a project

    1. From the main menu, select File | New | Project .
    2. Select New Project . Specify the name for the project, for example, junit-tutorial .
    3. Select IntelliJ as a build tool. In Language , select Java .
    4. 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 .
    5. Click Create .

    Add dependencies

    For our project to use JUnit features, we need to add JUnit as a dependency.

    Manually adding a testing library to a project

    1. From the main menu, select File | Project Structure ( Ctrl+Alt+Shift+S ) or click on the toolbar.
    2. Under Project Settings , select Libraries and click | From Maven .
    3. In the dialog that opens, specify the necessary library artifact, for example: org.junit.jupiter:junit-jupiter:5.9.1 .
    4. Apply the changes and close the dialog.

    The procedure above shows the ‘manual’ way so that you know what happens behind the scenes and where you set up the testing framework. However, if you just start writing tests, IntelliJ IDEA will automatically detect if the dependency is missing and prompt you to add it.

    Write application code

    Let’s add some code that we’ll be testing.

    1. In the Project tool window Alt+1 , go to src/main/java and create a Java file called Calculator.java .
    2. Paste the following code in the file:

    Create tests

    Now let’s create a test. A test is a piece of code whose function is to check if another piece of code is operating correctly. In order to do the check, it calls the tested method and compares the result with the predefined expected result . An expected result can be, for example, a specific return value or an exception.

    1. Place the caret at the Calculator class declaration and press Alt+Enter . Alternatively, right-click it and select Show Context Actions . From the menu, select Create Test . The code of the class that we are going to test
    2. Select the two class methods that we are going to test. The Create Test dialog
    3. The editor takes you to the newly created test class. Modify the add() test as follows:

    @Test @DisplayName(«Multiply two numbers») void multiply() < assertAll(() ->assertEquals(4, Calculator.multiply(2, 2)), () -> assertEquals(-4, Calculator.multiply(2, -2)), () -> assertEquals(4, Calculator.multiply(-2, -2)), () -> assertEquals(0, Calculator.multiply(1, 0))); >

    To navigate between the test and the code being tested, use the Ctrl+Shift+T shortcut.

    Run tests and view their results

    After we have set up the code for the testing, we can run the tests and find out if the tested methods are working correctly.

    The popup that appears after clicking on the Run icon in the gutter

    • To run an individual test, click in the gutter and select Run .
    • To run all tests in a test class, click against the test class declaration and select Run .

    You can view test results in the Run tool window.

    The results of the tests shown in the Run tool window

    IntelliJ IDEA hides passed tests by default. To see them, make sure the Show Passed option is enabled in the Run tool window.

    Источник

    Оцените статью