Unit Testing
Unit testing is a crucial part of the software development process. It involves testing individual units of code in isolation to ensure that they function correctly. The units can be methods, classes, or components that have a specific functionality.
In Java, unit testing is often done using frameworks like JUnit and TestNG. Let's take an example of a simple calculator class and write unit tests for its methods.
1class Calculator {
2 public int add(int a, int b) {
3 return a + b;
4 }
5
6 public int subtract(int a, int b) {
7 return a - b;
8 }
9}
10
11public class Main {
12 public static void main(String[] args) {
13 Calculator calculator = new Calculator();
14 int sum = calculator.add(5, 3);
15 int difference = calculator.subtract(8, 2);
16 System.out.println("Sum: " + sum);
17 System.out.println("Difference: " + difference);
18 }
19}
In this example, we have a Calculator
class with add
and subtract
methods. We create an instance of the Calculator
class and use the methods to perform addition and subtraction operations. We can write unit tests to verify that these methods return the expected results.
Unit testing helps in identifying and fixing bugs early in the development process. It also enables developers to refactor code with confidence, knowing that they have tests in place to verify the correctness of their changes.
When writing unit tests, it is important to cover different scenarios and edge cases to ensure that the code is robust and handles all possible inputs correctly.
xxxxxxxxxx
class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
int sum = calculator.add(5, 3);
int difference = calculator.subtract(8, 2);
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
}
}