Skip to content

Commit 9aae164

Browse files
committed
unit-testing-with-junit
1 parent 502d907 commit 9aae164

File tree

3 files changed

+213
-0
lines changed

3 files changed

+213
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
JUnit is a popular testing framework for Java that is widely used by developers to perform unit testing of Java applications. Here's an introduction to the JUnit framework:
2+
3+
## Introduction to JUnit
4+
5+
### What is JUnit?
6+
7+
JUnit is a simple, open-source framework designed for writing and running automated tests in Java. It provides a set of annotations and APIs for creating and executing test cases, assertions for verifying expected outcomes, and test runners for executing tests and reporting results.
8+
9+
### Key Features of JUnit
10+
11+
1. **Annotations**: JUnit provides annotations such as `@Test`, `@Before`, `@After`, `@BeforeClass`, and `@AfterClass` to define test methods and setup/teardown methods.
12+
13+
2. **Assertions**: JUnit provides a set of assertion methods in the `org.junit.Assert` class for validating expected outcomes in test cases.
14+
15+
3. **Test Runners**: JUnit supports different test runners for executing tests, including `JUnitCore`, `JUnit4`, and IDE integrations with Eclipse, IntelliJ IDEA, and NetBeans.
16+
17+
4. **Parameterized Tests**: JUnit allows you to run the same test method with different inputs by using parameterized tests.
18+
19+
5. **Exception Testing**: JUnit provides mechanisms for testing expected exceptions by using the `@Test` annotation's `expected` attribute or the `@Rule` annotation with `ExpectedException`.
20+
21+
### Example Test Class
22+
23+
```java
24+
import org.junit.*;
25+
26+
public class MyMathTest {
27+
28+
@BeforeClass
29+
public static void setUpClass() {
30+
// Setup once before any test methods run
31+
}
32+
33+
@AfterClass
34+
public static void tearDownClass() {
35+
// Cleanup once after all test methods have run
36+
}
37+
38+
@Before
39+
public void setUp() {
40+
// Setup before each test method
41+
}
42+
43+
@After
44+
public void tearDown() {
45+
// Cleanup after each test method
46+
}
47+
48+
@Test
49+
public void testAdd() {
50+
assertEquals(5, MyMath.add(2, 3));
51+
}
52+
53+
@Test
54+
public void testSubtract() {
55+
assertEquals(2, MyMath.subtract(5, 3));
56+
}
57+
58+
@Test(expected = ArithmeticException.class)
59+
public void testDivideByZero() {
60+
MyMath.divide(5, 0);
61+
}
62+
}
63+
```
64+
65+
### How to Use JUnit
66+
67+
1. **Add JUnit Dependency**: Include the JUnit library in your project's build path or dependency management tool (e.g., Maven, Gradle).
68+
69+
2. **Write Test Classes**: Create test classes with test methods annotated with `@Test` and perform assertions using JUnit's assertion methods.
70+
71+
3. **Run Tests**: Execute tests using a test runner such as JUnitCore or an IDE that supports JUnit (e.g., Eclipse, IntelliJ IDEA).
72+
73+
4. **Analyze Results**: Review test results to identify failures and errors, and debug issues in your code.
74+
75+
### Conclusion
76+
77+
JUnit is a powerful testing framework for Java that simplifies the process of writing and running automated tests. By following best practices and leveraging JUnit's features, developers can ensure the reliability and quality of their Java applications.
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
In JUnit, test suites allow you to group multiple test classes together to execute them as a single unit. Assertions are used to verify expected outcomes in test methods. Here's how you can work with test suites and assertions in JUnit:
2+
3+
### Test Suites
4+
5+
A test suite is a collection of test cases (i.e., test classes) that can be executed together. You can create a test suite to run multiple test classes at once.
6+
7+
```java
8+
import org.junit.runner.RunWith;
9+
import org.junit.runners.Suite;
10+
11+
@RunWith(Suite.class)
12+
@Suite.SuiteClasses({MyMathTest.class, OtherTest.class})
13+
public class AllTests {
14+
// This class is just a holder for the above annotations
15+
}
16+
```
17+
18+
### Assertions
19+
20+
JUnit provides a set of assertion methods in the `org.junit.Assert` class to verify expected outcomes in test methods.
21+
22+
```java
23+
import static org.junit.Assert.*;
24+
25+
public class MyMathTest {
26+
27+
@Test
28+
public void testAdd() {
29+
assertEquals(5, MyMath.add(2, 3)); // Verifies that the actual result is equal to the expected value
30+
}
31+
32+
@Test
33+
public void testSubtract() {
34+
assertTrue(MyMath.subtract(5, 3) == 2); // Verifies that the condition is true
35+
}
36+
37+
@Test
38+
public void testDivideByZero() {
39+
try {
40+
MyMath.divide(5, 0);
41+
fail("Expected ArithmeticException was not thrown"); // Fails the test if the expected exception is not thrown
42+
} catch (ArithmeticException e) {
43+
// Expected exception
44+
}
45+
}
46+
}
47+
```
48+
49+
### Common Assertion Methods
50+
51+
- `assertEquals(expected, actual)`: Verifies that the expected and actual values are equal.
52+
- `assertTrue(condition)`: Verifies that the given condition is true.
53+
- `assertFalse(condition)`: Verifies that the given condition is false.
54+
- `assertNull(object)`: Verifies that the given object is null.
55+
- `assertNotNull(object)`: Verifies that the given object is not null.
56+
- `assertThrows(expectedException, executable)`: Verifies that the executable throws the expected exception.
57+
58+
### Tips
59+
60+
- Choose appropriate assertion methods based on the type of condition you want to verify.
61+
- Use descriptive error messages to provide context when assertions fail.
62+
- Combine multiple assertions in a single test method to verify different aspects of the code.
63+
64+
By using test suites and assertions effectively in your JUnit tests, you can organize your tests efficiently and ensure that your code behaves as expected under different conditions.
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
To write and run tests with the JUnit framework, you can follow these steps:
2+
3+
### 1. Write Test Classes
4+
5+
Create test classes containing test methods annotated with `@Test` to specify which methods should be executed as tests. Use JUnit's assertion methods to validate the expected behavior of your code.
6+
7+
```java
8+
import org.junit.*;
9+
import static org.junit.Assert.*;
10+
11+
public class MyMathTest {
12+
13+
@Test
14+
public void testAdd() {
15+
assertEquals(5, MyMath.add(2, 3));
16+
}
17+
18+
@Test
19+
public void testSubtract() {
20+
assertEquals(2, MyMath.subtract(5, 3));
21+
}
22+
23+
@Test(expected = ArithmeticException.class)
24+
public void testDivideByZero() {
25+
MyMath.divide(5, 0);
26+
}
27+
}
28+
```
29+
30+
### 2. Compile Test Classes
31+
32+
Compile your test classes along with the classes being tested. Ensure that JUnit library is in your classpath.
33+
34+
### 3. Run Tests
35+
36+
Execute your tests using a test runner. You can use one of the following methods:
37+
38+
- **JUnit Runner**: Run tests programmatically using `JUnitCore` class.
39+
40+
```java
41+
import org.junit.runner.JUnitCore;
42+
import org.junit.runner.Result;
43+
import org.junit.runner.notification.Failure;
44+
45+
public class TestRunner {
46+
public static void main(String[] args) {
47+
Result result = JUnitCore.runClasses(MyMathTest.class);
48+
for (Failure failure : result.getFailures()) {
49+
System.out.println(failure.toString());
50+
}
51+
System.out.println(result.wasSuccessful());
52+
}
53+
}
54+
```
55+
56+
- **IDE Integration**: Run tests directly from your IDE (e.g., Eclipse, IntelliJ IDEA) by right-clicking on the test class and selecting "Run as JUnit Test".
57+
58+
- **Maven or Gradle**: Run tests using build automation tools like Maven or Gradle by executing test goals/tasks.
59+
60+
### 4. Analyze Results
61+
62+
Review the test results to identify any failures or errors. JUnit provides detailed information about which tests passed, which failed, and any exceptions that occurred during testing.
63+
64+
### Tips:
65+
66+
- Use `@Before` and `@After` annotations to execute setup and teardown methods before and after each test method.
67+
68+
- Utilize parameterized tests with `@RunWith(Parameterized.class)` for testing multiple inputs.
69+
70+
- Organize your test classes into separate packages and naming conventions (e.g., `MyClassTest`, `MyClassIntegrationTest`) for better organization.
71+
72+
By following these steps, you can effectively write and run tests using the JUnit framework to ensure the quality and reliability of your Java applications.

0 commit comments

Comments
 (0)