📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
How to organize Tests(JUnit Java Class files)
── pom.xml
└── src
├── main
│ ├── java
│ │ └── com
│ │ └── javadevelopersguide
│ │ └── junit
│ │ └── Calculator.java
│ ├── resources
└── test
├── java
│ └── com
│ └── javadevelopersguide
│ └── junit
│ └── CalculatorTest.java
└── resources
Package Naming Convention
Make sure that you write each test independent of all the others
Well, whenever you write multiple Unit tests then make sure that all the Unit tests are independent of each other. This will help you to identify the root cause and test the unit of logic properly.Try to use @BeforeEach and @AfterEach annotations to set up pre-requisites if any for all your test cases. The methods annotated with @BeforeEach and @AfterEach execute before and after respectively for each method annotated with @Test, @RepeatedTest, @ParameterizedTest, or @TestFactory in the current class.
Don't assume the order in which tests within a test case run
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestMethodOrder {
@Test
public void testA() {
System.out.println("first");
}
@Test
public void testB() {
System.out.println("second");
}
@Test
public void testC() {
System.out.println("third");
}
}
Cover single specific scenario in one JUnit test case
Use the most appropriate assertion methods
Always use proper assertions to verify the expected vs. actual results.JUnit has many assertion methods - assertEquals, assertTrue, assertFalse, assertNull, assertNotNull, assertArrayEquals, assertSame. Know the assertions in the latest version of JUnit and use the most appropriate one to have the most readable test code.
Put assertion parameters in the proper order
expected
actual
Use @BeforeEach and @AfterEach annotations
Don't initialize the object's in the constructor instead use @BeforeEach and @AfterEach annotation to set up and destroy the objects.The methods annotated with @BeforeEach and @AfterEach execute before and after respectively for each method annotated with @Test, @RepeatedTest, @ParameterizedTest, or @TestFactory in the current class.
JUnit Test Naming Conventions
Mock external services/dependencies
Happy Learning and Keep Coding !!!!.
Comments
Post a Comment
Leave Comment