- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
Guided: Unit Testing in Java SE
In this Code Lab, you will learn the fundamentals of unit testing in Java using the JUnit 5 framework. You will write a test suite for a simple `SavingsAccount` class, learning how to validate logic, test edge cases, and refactor code with confidence.
Lab Info
Table of Contents
-
Challenge
Introduction to Unit Testing
Welcome to this Code Lab on unit testing in Java! Unit testing is the practice of testing small, isolated pieces of your code—called "units"—to ensure they work correctly. A unit is typically a single method or class.
By writing unit tests, you create a safety net that allows you to make changes to your code with confidence, knowing that if you break something, a test will fail. In this lab, you'll use JUnit 5, the most popular testing framework for Java.
You'll be working with a simple
SavingsAccountclass. Your job is to write a suite of tests to verify its behavior, find a bug, fix it, and confirm that your fix didn't break anything else.info> This lab experience was developed by the Pluralsight team using Forge, an internally developed AI tool utilizing Gemini technology. All sections were verified by human experts for accuracy prior to publication. For issue reporting, please contact us.
-
Challenge
Writing Your First Test
Start by creating your test class and writing your first test case. A test class is a companion to the class it's testing and holds all the related test methods. In JUnit 5, any method annotated with
@Testis recognized as a test case.The core of any test is an assertion. An assertion is a statement that checks whether a condition is true. If the condition is false, the test fails. JUnit provides a rich set of assertion methods in the
org.junit.jupiter.api.Assertionsclass, such asassertEquals,assertTrue, andassertNotNull. -
Challenge
Testing Core Logic
A good test suite covers all the primary functions of a class. Now that you've tested deposits, add tests for other core logic: successful withdrawals and the initial state of the account upon creation. Each test should remain focused on a single piece of functionality.
-
Challenge
Testing Edge Cases and Failures
Beyond the happy path, it's crucial to test edge cases—the boundaries and special conditions of your logic. What happens when you withdraw the exact balance? What should happen when you try to withdraw more than you have?
For expected failures, like an overdraft attempt, you can't just use
assertEquals. Instead, JUnit providesassertThrows, which asserts that a specific piece of code throws a specific type of exception. This is key to ensuring your application handles errors gracefully. -
Challenge
Refactoring with Confidence
Your test for overdraft protection should have failed! This is great news—it means your test has successfully found a bug in the code. This is the principle behind Test-Driven Development (TDD): write a failing test, then write the code to make it pass.
Now you will fix the bug in the
SavingsAccountclass. Once you've implemented the fix, you'll re-run the entire test suite. This ensures that your change not only fixed the bug but also didn't accidentally break other parts of the application (a regression). This is how unit tests give you the confidence to refactor and improve your code. After fixing the bug, you can ensure that your change didn't break any existing functionality by running the tests. This is called regression testing, and it's where a full test suite provides immense value.Run the tests in the Terminal with the command
mvn testand observe how all tests, including the previously failingtestOverdraftProtectiontest, now pass. This confirms your fix was successful and did not introduce any new issues. -
Challenge
Conclusion
Congratulations on completing the lab! You've learned the fundamentals of unit testing with JUnit 5. You have successfully:
- Written effective JUnit test cases for 'happy path' scenarios.
- Validated method logic and crucial edge cases.
- Used tests to identify a bug, implement a fix, and increase your confidence that the change was safe.
These skills are essential for any professional developer to build robust, reliable, and maintainable applications.
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.