SlideShare a Scribd company logo
JUNIT BASICS
JUNIT BASICS
TESTING EXCEPTIONS, JUNIT HOOKS
TESTING EXCEPTIONS
• Testing exceptions in JUnit is essential to ensure that certain parts of code behave as expected and
throw the correct exceptions when necessary.
• JUnit provides different ways to test for exceptions.
• Some common techniques using JUnit 4 and JUnit 5.
3
TESTING EXCEPTIONS
public class MyMath {
public int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
return a / b;
}
}
java
Assuming you have a method that might throw an exception:
4
TESTING EXCEPTIONS
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class MyMathTest {
@Test(expected = ArithmeticException.class)
public void testDivideByZero() {
MyMath myMath = new MyMath();
myMath.divide(10, 0);
}
java
1. Using JUnit 4 @Test with expected attribute:
5
TESTING EXCEPTIONS
@Test
public void testValidDivision() {
MyMath myMath = new MyMath();
int result = myMath.divide(10, 2);
assertEquals(5, result);
}
}
Java(Cont…)
1. Using JUnit 4 @Test with expected attribute:
6
TESTING EXCEPTIONS
• In the testDivideByZero method, the divide method will throw an ArithmeticException when
dividing by zero.
• Using the expected attribute of the @Test annotation, this exception should be thrown during the
test is indicated.
• In the testValidDivision method, the divide method will perform a valid division when the
denominator is not zero.
• assertEquals is used to verify that the result is as expected.
7
TESTING EXCEPTIONS
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class MyMathTest {
@Test
public void testDivideByZero() {
MyMath myMath = new MyMath();
assertThrows(ArithmeticException.class, () -> myMath.divide(10, 0));
}
java
2. Using JUnit 5 assertThrows method:
8
TESTING EXCEPTIONS
@Test
public void testValidDivision() {
MyMath myMath = new MyMath();
int result = myMath.divide(10, 2);
assertEquals(5, result);
}
}
Java(Cont…)
2. Using JUnit 5 assertThrows method:
9
TESTING EXCEPTIONS
• With JUnit 5, use the assertThrows method, which takes the expected exception class and a lambda
expression representing the code that should throw the exception.
• If the specified exception is thrown during the lambda execution, the test passes.
Both approaches are valid for testing exceptions in JUnit.
But latest version is best
10
JUNIT HOOKS
• JUnit doesn't have built-in hooks in the same way that some other testing frameworks do.
• However, it provides annotations and methods that can be used to perform setup and teardown
actions before and after test methods or test classes are executed.
• These actions can serve a similar purpose as hooks in other testing frameworks.
11
JUNIT HOOKS
• In JUnit 4, the commonly used setup and teardown methods are @Before and @After, respectively.
• In JUnit 5, the equivalent annotations are @BeforeEach and @AfterEach.
• Additionally, there are class-level setup and teardown methods in JUnit 4 (@BeforeClass and
@AfterClass) and JUnit 5 (@BeforeAll and @AfterAll).
12
JUNIT HOOKS
• @BeforeClass: Used with static methods to perform setup actions before any test method is
executed in the test class. The method is executed only once per test class.
• @Before: Used to perform setup actions before each test method in the test class.
Here's an overview of these annotations:
JUnit 4 Hooks:
13
JUNIT HOOKS
• @After: Used to perform cleanup actions after each test method in the test class.
• @AfterClass: Used with static methods to perform cleanup actions after all test
methods have been executed in the test class. The method is executed only once
per test class.
Here's an overview of these annotations:
JUnit 4 Hooks:
14
JUNIT HOOKS
import org.junit.*;
public class MyTestClass {
@BeforeClass
public static void setUpClass() {
// Code to set up resources or configurations before all test methods }
@Before
public void setUp() {
// Code to set up resources or configurations before each test method }
@Test
public void testMethod1() {
// Test method 1 }
Java
Example usage in JUnit 4:
15
JUNIT HOOKS
@Test
public void testMethod2() {
// Test method 2 }
@After
public void tearDown() {
// Code to release resources or clean up after each test method }
@AfterClass
public static void tearDownClass() {
// Code to perform cleanup after all test methods have been executed
} }
Java(Cont…)
Example usage in JUnit 4:
16
JUNIT HOOKS
• @BeforeAll: Used with static methods to perform setup actions before any test
method is executed in the test class. The method is executed only once per test
class.
• @BeforeEach: Used to perform setup actions before each test method in the test
class.
JUnit 5 Hooks:
17
JUNIT HOOKS
• @AfterEach: Used to perform cleanup actions after each test method in the test
class.
• @AfterAll: Used with static methods to perform cleanup actions after all test
methods have been executed in the test class. The method is executed only once
per test class.
JUnit 5 Hooks:
18
JUNIT HOOKS
import org.junit.jupiter.api.*;
public class MyTestClass {
@BeforeAll
public static void setUpClass() {
// Code to set up resources or configurations before all test methods }
@BeforeEach
public void setUp() {
// Code to set up resources or configurations before each test method }
@Test
public void testMethod1() {
// Test method 1 }
Java
Example usage in JUnit 5:
19
JUNIT HOOKS
@Test
public void testMethod2() {
// Test method 2 }
@AfterEach
public void tearDown() {
// Code to release resources or clean up after each test method }
@AfterAll
public static void tearDownClass() {
// Code to perform cleanup after all test methods have been executed
} }
Java(Cont…)
Example usage in JUnit 5:
20
JUNIT HOOKS
• These setup and teardown methods provide a way to perform common
actions across test methods, such as setting up a test database,
initializing test data, or cleaning up resources after tests are done.
21

More Related Content

PPT
3 j unit
PPTX
Testing with Junit4
PPTX
Introduction to JUnit
PDF
junit-160729073220 eclipse software testing.pdf
PPSX
PPTX
JUnit- A Unit Testing Framework
3 j unit
Testing with Junit4
Introduction to JUnit
junit-160729073220 eclipse software testing.pdf
JUnit- A Unit Testing Framework

Similar to Session 4 -Junit- Testing Exceptions, Junit hooks.pptx (20)

PPTX
Software Testing and JUnit and Best Practices
PDF
Unit testing with Junit
PPTX
unit 1 (1).pptx
DOCX
Junit With Eclipse
PPTX
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
PPTX
8-testing.pptx
PPT
PPT
05 junit
PDF
JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...
PPS
JUnit Presentation
PPS
J unit presentation
PPTX
Unit Testing in Java
PPTX
Migrating to JUnit 5
PDF
What is new in JUnit5
PDF
PPTX
Junit4&testng presentation
PPTX
PPTX
Junit 5 - Maior e melhor
PPT
disc-c-presentation Unit testing at glance.ppt
PPTX
JUnit 5 - from Lambda to Alpha and beyond
Software Testing and JUnit and Best Practices
Unit testing with Junit
unit 1 (1).pptx
Junit With Eclipse
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
8-testing.pptx
05 junit
JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...
JUnit Presentation
J unit presentation
Unit Testing in Java
Migrating to JUnit 5
What is new in JUnit5
Junit4&testng presentation
Junit 5 - Maior e melhor
disc-c-presentation Unit testing at glance.ppt
JUnit 5 - from Lambda to Alpha and beyond
Ad

More from trainingdecorpo (7)

PPTX
AZURE CLOUD ARCHITECsdfsdsdfsdfsdfTURE.pptx
PPTX
Module2jxcnckvjzdxcnvkzjxnvkdsnfkvzsdf.pptx
PPTX
Module3ksjdfbsdkfkasjdfbjkendfksdmnfckajs.pptx
PPTX
AZURE CLOUD ARCHITECTUREMADEBYMEITISTHE.pptx
PPTX
Session 3 - SPRING BOOT - Accessing Actuator EndPoint.pptx
PPTX
Session 4 Try with Resources and Custom Exception.pptx
PPTX
Session 2 BufferReaderBestOnReaderand.pptx
AZURE CLOUD ARCHITECsdfsdsdfsdfsdfTURE.pptx
Module2jxcnckvjzdxcnvkzjxnvkdsnfkvzsdf.pptx
Module3ksjdfbsdkfkasjdfbjkendfksdmnfckajs.pptx
AZURE CLOUD ARCHITECTUREMADEBYMEITISTHE.pptx
Session 3 - SPRING BOOT - Accessing Actuator EndPoint.pptx
Session 4 Try with Resources and Custom Exception.pptx
Session 2 BufferReaderBestOnReaderand.pptx
Ad

Recently uploaded (20)

PDF
08_Mango_Dis_PARTIALSTEMPARASITE.pdf -farmers
PDF
Chapter 04 - Osseous Systefsdm - Copy.pdf
PDF
HealthyIndianBites:Eat Right, Live Right.pdf
PDF
Food in the Maldives and Its Unique Culinary Tradition
PPTX
Το κρασί από την αρχαιότητα έως σήμερα.pptx
PPTX
FST-401 lecture # 12 food chemistry.pptx
PPTX
Arunish chawla 23212AGC218 B.Sc. Ag. THIRD YEAR (2).pptx
PPTX
Planetary Food Systems and Climate Change.pptx
PPTX
Agrisphere ai powered presision farming marketplace
PPTX
W1 - Intro to Poetry.pptxbhjbhjhvghcgcgfcgc
PPT
why_study_financial_markets_ggghgftytfytftfyt.ppt
PPTX
students copy Fundamendals of Cookery final.pptx
PPTX
Food-Sanitation-and-Microbiology_20250801_223934_0000.pptx
PPTX
SEAFOOD IRRADIATION – TECHNOLOGY AND APPLICATION.pptx
PDF
How Food Data Scraping Is Revolutionizing Restaurant Growth Strategies
PDF
Brown-Illustrative-Abstract-Group-Project-Presentation-1.pdf
PDF
PREPARE SALAD & SALD DRESSING cookery 1.
PPTX
BARTENDING-03-Cocktail-Recipesqq(1).pptx
PPT
Fall Ladder Safety - Training Slide photos.ppt
PPTX
how How_to_Wash_Dishes_with_Finesse.pptx
08_Mango_Dis_PARTIALSTEMPARASITE.pdf -farmers
Chapter 04 - Osseous Systefsdm - Copy.pdf
HealthyIndianBites:Eat Right, Live Right.pdf
Food in the Maldives and Its Unique Culinary Tradition
Το κρασί από την αρχαιότητα έως σήμερα.pptx
FST-401 lecture # 12 food chemistry.pptx
Arunish chawla 23212AGC218 B.Sc. Ag. THIRD YEAR (2).pptx
Planetary Food Systems and Climate Change.pptx
Agrisphere ai powered presision farming marketplace
W1 - Intro to Poetry.pptxbhjbhjhvghcgcgfcgc
why_study_financial_markets_ggghgftytfytftfyt.ppt
students copy Fundamendals of Cookery final.pptx
Food-Sanitation-and-Microbiology_20250801_223934_0000.pptx
SEAFOOD IRRADIATION – TECHNOLOGY AND APPLICATION.pptx
How Food Data Scraping Is Revolutionizing Restaurant Growth Strategies
Brown-Illustrative-Abstract-Group-Project-Presentation-1.pdf
PREPARE SALAD & SALD DRESSING cookery 1.
BARTENDING-03-Cocktail-Recipesqq(1).pptx
Fall Ladder Safety - Training Slide photos.ppt
how How_to_Wash_Dishes_with_Finesse.pptx

Session 4 -Junit- Testing Exceptions, Junit hooks.pptx

  • 3. TESTING EXCEPTIONS • Testing exceptions in JUnit is essential to ensure that certain parts of code behave as expected and throw the correct exceptions when necessary. • JUnit provides different ways to test for exceptions. • Some common techniques using JUnit 4 and JUnit 5. 3
  • 4. TESTING EXCEPTIONS public class MyMath { public int divide(int a, int b) { if (b == 0) { throw new ArithmeticException("Division by zero is not allowed."); } return a / b; } } java Assuming you have a method that might throw an exception: 4
  • 5. TESTING EXCEPTIONS import org.junit.Test; import static org.junit.Assert.assertEquals; public class MyMathTest { @Test(expected = ArithmeticException.class) public void testDivideByZero() { MyMath myMath = new MyMath(); myMath.divide(10, 0); } java 1. Using JUnit 4 @Test with expected attribute: 5
  • 6. TESTING EXCEPTIONS @Test public void testValidDivision() { MyMath myMath = new MyMath(); int result = myMath.divide(10, 2); assertEquals(5, result); } } Java(Cont…) 1. Using JUnit 4 @Test with expected attribute: 6
  • 7. TESTING EXCEPTIONS • In the testDivideByZero method, the divide method will throw an ArithmeticException when dividing by zero. • Using the expected attribute of the @Test annotation, this exception should be thrown during the test is indicated. • In the testValidDivision method, the divide method will perform a valid division when the denominator is not zero. • assertEquals is used to verify that the result is as expected. 7
  • 8. TESTING EXCEPTIONS import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; public class MyMathTest { @Test public void testDivideByZero() { MyMath myMath = new MyMath(); assertThrows(ArithmeticException.class, () -> myMath.divide(10, 0)); } java 2. Using JUnit 5 assertThrows method: 8
  • 9. TESTING EXCEPTIONS @Test public void testValidDivision() { MyMath myMath = new MyMath(); int result = myMath.divide(10, 2); assertEquals(5, result); } } Java(Cont…) 2. Using JUnit 5 assertThrows method: 9
  • 10. TESTING EXCEPTIONS • With JUnit 5, use the assertThrows method, which takes the expected exception class and a lambda expression representing the code that should throw the exception. • If the specified exception is thrown during the lambda execution, the test passes. Both approaches are valid for testing exceptions in JUnit. But latest version is best 10
  • 11. JUNIT HOOKS • JUnit doesn't have built-in hooks in the same way that some other testing frameworks do. • However, it provides annotations and methods that can be used to perform setup and teardown actions before and after test methods or test classes are executed. • These actions can serve a similar purpose as hooks in other testing frameworks. 11
  • 12. JUNIT HOOKS • In JUnit 4, the commonly used setup and teardown methods are @Before and @After, respectively. • In JUnit 5, the equivalent annotations are @BeforeEach and @AfterEach. • Additionally, there are class-level setup and teardown methods in JUnit 4 (@BeforeClass and @AfterClass) and JUnit 5 (@BeforeAll and @AfterAll). 12
  • 13. JUNIT HOOKS • @BeforeClass: Used with static methods to perform setup actions before any test method is executed in the test class. The method is executed only once per test class. • @Before: Used to perform setup actions before each test method in the test class. Here's an overview of these annotations: JUnit 4 Hooks: 13
  • 14. JUNIT HOOKS • @After: Used to perform cleanup actions after each test method in the test class. • @AfterClass: Used with static methods to perform cleanup actions after all test methods have been executed in the test class. The method is executed only once per test class. Here's an overview of these annotations: JUnit 4 Hooks: 14
  • 15. JUNIT HOOKS import org.junit.*; public class MyTestClass { @BeforeClass public static void setUpClass() { // Code to set up resources or configurations before all test methods } @Before public void setUp() { // Code to set up resources or configurations before each test method } @Test public void testMethod1() { // Test method 1 } Java Example usage in JUnit 4: 15
  • 16. JUNIT HOOKS @Test public void testMethod2() { // Test method 2 } @After public void tearDown() { // Code to release resources or clean up after each test method } @AfterClass public static void tearDownClass() { // Code to perform cleanup after all test methods have been executed } } Java(Cont…) Example usage in JUnit 4: 16
  • 17. JUNIT HOOKS • @BeforeAll: Used with static methods to perform setup actions before any test method is executed in the test class. The method is executed only once per test class. • @BeforeEach: Used to perform setup actions before each test method in the test class. JUnit 5 Hooks: 17
  • 18. JUNIT HOOKS • @AfterEach: Used to perform cleanup actions after each test method in the test class. • @AfterAll: Used with static methods to perform cleanup actions after all test methods have been executed in the test class. The method is executed only once per test class. JUnit 5 Hooks: 18
  • 19. JUNIT HOOKS import org.junit.jupiter.api.*; public class MyTestClass { @BeforeAll public static void setUpClass() { // Code to set up resources or configurations before all test methods } @BeforeEach public void setUp() { // Code to set up resources or configurations before each test method } @Test public void testMethod1() { // Test method 1 } Java Example usage in JUnit 5: 19
  • 20. JUNIT HOOKS @Test public void testMethod2() { // Test method 2 } @AfterEach public void tearDown() { // Code to release resources or clean up after each test method } @AfterAll public static void tearDownClass() { // Code to perform cleanup after all test methods have been executed } } Java(Cont…) Example usage in JUnit 5: 20
  • 21. JUNIT HOOKS • These setup and teardown methods provide a way to perform common actions across test methods, such as setting up a test database, initializing test data, or cleaning up resources after tests are done. 21