Writing & Running JUnits With Intellij & Gradle

Stuti Jain
2 min readMar 5, 2021

--

Prerequisites

  • You have created a Java project in IntelliJ IDEA.
  • You have JUnit 4 or JUnit5 on the classpath, either by adding a test library, or adding a dependency in Gradle.

Creating Your First Test

  1. In your production code in the editor, place the caret at the class for which you want to create a test, press ⌥⏎ / Alt+Insert, and select Create Test.
  2. Select Test Method | JUnit 4 from the menu. Select methods that you want to test.

Writing the Test Body

  1. Write your tests describing what you want to achieve. For example in above code we want to get domain.

Iterate

Developing code is an iterative process.

  1. Pick a second test case that specifies more requirements of the method you’re testing.
  2. For example in our case various test cases for the method can be domain is found , not found, host can be null ….
  3. Continue writing the test bodies, including scenarios as methods that you need.

Running the Tests using Intellij

If your source and test roots are correctly configured — source roots will appear as blue folders, test folders will have a green background.
click the gutter icon next to the test class or test method.
Alternatively, Click on the Run toolbar to rerun all tests in a session.

Running the Tests using Gradle

# Executes all tests in SuffixBasedDomainExtractorTest
gradle test --tests SuffixBasedDomainExtractorTest

# Executes a single specified test in SuffixBasedDomainExtractorTest
gradle test --tests SuffixBasedDomainExtractorTest.testExtractDomainGoogle
# Executes all tests in folder
gradle test

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response