Testing with junit...
tell me in simple way
JUnit is a testing framework in Java used to check if your code
is working correctly. It helps you write test cases to verify that
methods in your program return expected results.
Steps to Use JUnit:
1. Add JUnit to Your Project – If using Maven, add this to
pom.xml:
xml
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
If using JUnit 5:
xml
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
2. Write a Simple Java Class to Test:
java
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
3. Create a JUnit Test Class:
java
import org.junit.Test;
import static org.junit.Assert.*;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calc = new Calculator();
assertEquals(5, calc.add(2, 3)); // Checking if 2+3 equals
5
}
}
4. Run the Test:
o If using an IDE like IntelliJ or Eclipse, right-click the
test class and choose Run as JUnit Test.
o If using Maven, run:
bash
mvn test
o If using Gradle, run:
bash
gradle test
If the test passes, it means your method is working fine. If it
fails, JUnit will show an error, and you can fix your code.
Would you like an example with more advanced features like
parameterized tests or mocking?
JUnit in Simple Terms
JUnit is a Java testing framework that helps you automate the
testing process to check if your code works correctly. Instead
of manually running and checking your program, JUnit runs
tests automatically and shows if something is wrong.
Why Use JUnit?
✅ Helps catch errors early in development
✅ Automates repetitive testing
✅ Ensures that changes to code don’t break existing
functionality
✅ Works well with tools like Maven, Gradle, and CI/CD
pipelines
Basic JUnit Concepts
1. Test Methods (@Test)
A test method is a simple function that checks if a part of
your code works as expected.
Example:
java
import org.junit.Test;
import static org.junit.Assert.*;
public class CalculatorTest {
@Test // Marks this method as a test
public void testAddition() {
Calculator calc = new Calculator();
assertEquals(5, calc.add(2, 3)); // Checking if 2+3 = 5
}
}
✅ If the test passes, JUnit shows a green bar (success).
❌ If the test fails, JUnit shows a red bar (failure).
2. Assertions (Checking Results)
Assertions are methods that verify expected vs. actual
output.
Assertion Method Description
assertEquals(expected, actual) Checks if two values are equal
assertTrue(condition) Passes if condition is true
assertFalse(condition) Passes if condition is false
assertNull(object) Passes if object is null
assertNotNull(object) Passes if object is NOT null
Example:
java
@Test
public void testMultiplication() {
assertEquals(20, 4 * 5); // Passes because 4 * 5 = 20
assertTrue(10 > 5); // Passes because 10 is greater than
5
}
3. Before and After (@Before and @After)
JUnit allows setup and cleanup before and after every test.
java
import org.junit.*;
public class SampleTest {
@Before // Runs before each test
public void setup() {
System.out.println("Setup before test...");
}
@After // Runs after each test
public void cleanup() {
System.out.println("Cleanup after test...");
}
@Test
public void testSomething() {
System.out.println("Running test...");
}
}
Output:
bash
Setup before test...
Running test...
Cleanup after test...
4. Testing Exceptions (@Test(expected = Exception.class))
Sometimes, we want to test if a method throws an exception
correctly.
Example:
java
@Test(expected = ArithmeticException.class)
public void testDivideByZero() {
int result = 10 / 0; // This should throw an exception
}
✅ The test passes if the expected exception occurs.
❌ The test fails if no exception is thrown.
5. Parameterized Tests (Running Multiple Cases Easily)
JUnit allows testing with multiple values without writing
duplicate code.
Example:
java
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.*;
@RunWith(Parameterized.class)
public class ParameterizedTest {
private int input;
private int expected;
public ParameterizedTest(int input, int expected) {
this.input = input;
this.expected = expected;
}
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ 2, 4 }, { 3, 9 }, { 4, 16 } // Input → Expected Output
});
}
@Test
public void testSquare() {
assertEquals(expected, input * input);
}
}
✅ This test will automatically run for each input set {2→4,
3→9, 4→16}.
6. Ignoring Tests (@Ignore)
If a test is not ready, you can temporarily disable it.
java
import org.junit.Ignore;
@Ignore("Skipping this test for now")
@Test
public void testFeatureX() {
assertEquals(10, 5 * 2);
}
✅ The test will be ignored during execution.
7. Running Tests in a Suite (@RunWith(Suite.class))
JUnit can group multiple test classes and run them together.
java
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
CalculatorTest.class, // Add test classes here
SampleTest.class
})
public class TestSuite { }
✅ Running TestSuite.class will execute all included test cases.
Running JUnit Tests
Using IDE: Right-click test class → Run as JUnit Test
Using Maven: Run
bash
mvn test
Using Gradle: Run
bash
gradle test
JUnit 4 vs. JUnit 5
Feature JUnit 4 JUnit 5
Test @Test
@Test (org.junit)
Annotation (org.junit.jupiter.api)
Parameteri @RunWith(Parameterize
@ParameterizedTest
zed Tests d.class)
Exception @Test(expected = assertThrows(Exceptio
Testing Exception.class) n.class, () -> {...})
Nested ✅ Supported
❌ Not Supported
Tests (@Nested)
If using JUnit 5, add this Maven dependency:
xml
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
Summary
✅ JUnit is used for testing Java code automatically.
✅ Assertions (assertEquals, assertTrue) check if the output is
correct.
✅ Annotations (@Test, @Before, @After) manage test
execution.
✅ Parameterized tests help run multiple cases easily.
✅ JUnit integrates with Maven, Gradle, and CI/CD pipelines.