To Examples Page

Creating a JUnit5 Test Class

Example: Create a JUnit5 Test class for the Greeter Class

  1. In the source code file Greeter.java, place the cursor on the name Greeter in the line
    public class Greeter {
    
    Note: if you are creating a test file for a class that does not have a class source code file in the module (for example the String or Calendar class in the Java Class Library), first create a dummy class, for example with name FakeClass in the source code file FakeClass.java.
  2. Press the keys Alt+Enter. Select Create Test.
  3. In the Create Test Dialog:
    1. Select JUnit5 as the Testing Library.
    2. In response to JUnit5 Library not found in the module, press the Fix button. Click OK on the Download Library from Maven Repository.
    3. Enter the test class name, for example: GreeterTest.
    4. In the Generate section, check the setup/@Before box.
    5. Check the boxes for the methods in the original class for which you want to generate test methods, for example makeGreeting in the Greeter class.
    6. Click OK. This source code is generated for the GreeterTest class:
      import static org.junit.jupiter.api.Assertions.*;
      class GreeterTest {
      
          @org.junit.jupiter.api.BeforeEach
          void setUp() {
          }
      
          @org.junit.jupiter.api.Test
          void makeGreeting() {
          }
      }
      
    7. Use Alt-Enter to fix this unit test code, for example:
      (1) Add library 'JUnit5.2" library to class path,
      (2) Replace qualified name with import:
      import org.junit.jupiter.api.BeforeEach;
      import org.junit.jupiter.api.Test;
      import static org.junit.jupiter.api.Assertions.*;
      
      class GreeterTest {
      
          @BeforeEach
          void setUp() {
          }
      
          @Test
          void makeGreeting() {
          }
      }
      
    8. Change the name of makeGreeting to test1.
    9. Add bodies to the methods:
      import org.junit.jupiter.api.BeforeEach;
      import org.junit.jupiter.api.Test;
      import static org.junit.jupiter.api.Assertions.*;
      
      class GreeterTest {
      
          @BeforeEach
          void setUp() {
              // This method initializes objects that
              // are used in each test method.
              // This method is not needed for the
              // GreeterTest class. 
          }
      
          @Test
          void test1( ) {
              assertEquals("Hello, Alice, how are you?",
                  Greeter.makeGreeting("Alice");
          }
      }
      
    10. Run the unit test or tests. A green checkmark within a green circle means that a test passed (ran correctly).