Lab Practical: Unit Testing using JUnit
Objective:
To learn the fundamentals of unit testing and practice writing and executing JUnit test cases
to ensure individual units of code function correctly.
Outcomes:
- Understand the importance of unit testing in software development.
- Learn how to write JUnit test cases for Java programs.
- Execute test cases and interpret results.
- Improve code reliability through test-driven development practices.
Software/Tools Required:
- Java JDK (v8 or higher)
- JUnit (v4 or v5)
- IDE with JUnit support (Eclipse, IntelliJ IDEA, or VS Code)
- Maven or Gradle (for dependency management, optional)
Theory Brief:
Unit testing is a software testing technique where individual units or components of a
program are tested in isolation to ensure they work as intended. JUnit is a widely-used
testing framework for Java that allows developers to write repeatable tests to verify the
correctness of their code.
Procedure:
Step 1: Set up the Development Environment
Install Java JDK and your preferred IDE.
Create a new Java project in the IDE.
Add JUnit library (v4 or v5) to the project dependencies.
Step 2: Create a Java Class
Write a simple Java class with methods to be tested. Example: Calculator class with add,
subtract methods.
Step 3: Write JUnit Test Cases
Create a new test class in the test directory.
Use @Test annotation to define test methods.
Use assertions to validate expected outcomes (e.g., assertEquals).
Step 4: Run the Tests
Use IDE or command line to run JUnit tests.
Review the output to identify passed and failed tests.
Step 5: Debug and Refactor
Fix any issues found during testing.
Re-run the test cases to verify the fixes.
Sample Code:
Java Class (Calculator.java):
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
}
JUnit Test Class (CalculatorTest.java):
import static org.junit.Assert.*;
import org.junit.Test;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calc = new Calculator();
assertEquals(5, calc.add(2, 3));
}
@Test
public void testSubtract() {
Calculator calc = new Calculator();
assertEquals(1, calc.subtract(3, 2));
}
}
Viva Questions:
1. What is unit testing?
2. What is the purpose of JUnit?
3. How do you write a test case in JUnit?
4. What is the difference between @Before, @After, and @Test annotations?
5. Why are assertions used in test cases?
Evaluation Criteria:
Task Marks
Java class implementation 5
JUnit test case writing 5
Successful execution of test cases 5
Bug fixing and re-testing 5
Viva performance 5
Total 25