Skip to main content

Unit Testing in Java – Beginner Friendly Guide

Unit Testing in Java – Beginner Friendly Guide
Beginner Friendly

Unit Testing in Java – A Simple, Beginner Friendly Guide

Unit testing is one of the most important skills every Java developer should learn early. It saves time, improves code quality, and is expected in interviews at most modern companies.

What is Unit Testing?

Unit testing means writing small automated tests that verify whether a specific method or function is working correctly. Each test focuses on one “unit” of behavior.

Why Should You Learn Unit Testing?

  • You catch bugs early
  • You write cleaner and modular code
  • You refactor with confidence
  • Most product companies expect basic testing knowledge

Tools You Need (JUnit 5)

JUnit 5 is the most commonly used Java testing framework.

For Maven Projects

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.9.1</version>
    <scope>test</scope>
</dependency>

Your First Example – Calculator Class

Let’s test a simple 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; }
  public int multiply(int a, int b) { return a * b; }
  public int divide(int a, int b) {
    if (b == 0) throw new IllegalArgumentException("Cannot divide by zero");
    return a / b;
  }
}

CalculatorTest.java (JUnit 5)

import org.junit.jupiter.api.*;

public class CalculatorTest {

  private Calculator calculator;

  @BeforeEach
  void init() {
    calculator = new Calculator();
  }

  @Test
  void testAdd() {
    Assertions.assertEquals(8, calculator.add(5, 3));
  }

  @Test
  void testSubtract() {
    Assertions.assertEquals(6, calculator.subtract(10, 4));
  }

  @Test
  void testMultiply() {
    Assertions.assertEquals(10, calculator.multiply(2, 5));
  }

  @Test
  void testDivide() {
    Assertions.assertEquals(5, calculator.divide(10, 2));
  }

  @Test
  void testDivideByZero() {
    Assertions.assertThrows(IllegalArgumentException.class,
      () -> calculator.divide(10, 0));
  }
}
Pro Tip: Write one test for one behavior. This ensures clear, readable tests and easier debugging.

How to Run Tests

  • Right-click test → Run (IntelliJ/Eclipse)
  • Maven: mvn test
  • Gradle: gradle test

Best Practices

  • Follow Arrange → Act → Assert
  • Do not test too many things in one method
  • Avoid external systems (DB, APIs)
  • Use mocks for dependencies
  • Cover edge cases

What to Learn Next

  • Mockito (mocking dependencies)
  • TDD (Test Driven Development)
  • JaCoCo for coverage
  • Integration tests

Comments

Popular posts from this blog

πŸš€ Backend Development Resources – Your Learning Roadmap

Backend development is the backbone of every modern application. If you’re just getting started, don’t worry about mastering everything at once. Instead, focus on building apps , grasping fundamental concepts , and slowly growing your knowledge. πŸ‘‰ Mastery takes years, but having working knowledge of key tools and technologies is enough to land your first backend role. Below is a curated list of essential backend resources to guide your journey. πŸ’» Programming Languages 1. Java One of the most widely used backend languages. πŸ“Ί Telusko YouTube Channel (Java Playlist) 2. Kotlin Modern, concise, and gaining popularity, especially with Spring Boot. πŸ“Ί FreeCodeCamp – Kotlin Full Course ⚡ Frameworks Spring Boot A powerful framework for building production-ready applications. πŸ“Ί Java Brains – Spring Boot Playlist πŸ—„️ Databases SQL – PostgreSQL πŸ“Ί FreeCodeCamp – Postgres Full Course NoSQL – MongoDB πŸ“Ί Net Ninja – MongoDB Playlist πŸ”— ORM (Object Relational Mapping) JP...

Top 30 Must-Do DSA Problems for SDE Interviews

Top 30 Must-Do DSA Problems for SDE Interviews Here’s a curated list of 30 essential DSA problems that cover arrays, strings, linked lists, trees, stacks, queues, hashing, and searching/sorting. Solving these will prepare you for 60–70% of coding rounds for fresher and early SDE roles. Arrays Two Sum Best Time to Buy and Sell Stock Contains Duplicate Reverse Array (DIY) Rotate Array Maximum Subarray Strings Valid Palindrome Valid Anagram Longest Substring Without Repeating Characters Reverse Words in a String Linked List Reverse Linked List Linked List Cycle Merge Two Sorted Lists Middle of the Linked List Trees Maximum Depth of Binary Tree Binary Tree Level Order Traversal Validate Binary Search Tree Sorting & Searching Quick Sort (DIY Implementation) Merge Sort (DIY Implementation) Binary Search Stacks & Queues Implement Queue using Stacks Valid Parentheses Hashing & Misc M...

Ultimate Learning Path for Aspiring Software Engineers

πŸš€ Ultimate Learning Path for Aspiring Software Engineers Breaking into software engineering can feel overwhelming — especially when you’re just starting out. But with the right plan and structured resources, you can go from absolute beginner to job-ready developer faster than you think. Here’s a simple, practical roadmap I highly recommend πŸ‘‡ 🧩 Step 1: Start with Easy Coding Questions If you’re an absolute beginner , don’t rush into complex data structures yet. Begin with easy coding problems — the goal is to build confidence and learn to convert your thoughts into code . πŸ‘‰ Focus on: Practicing syntax and logic flow Understanding problem statements Writing clean, working code on your own This stage will strengthen your fundamentals and make your thinking-to-code conversion faster. πŸ’‘ Step 2: Master the Basics with Blind 75 Once you’re comfortable with basic coding, move to the legendary Blind 75 list — a carefully curated set of questions covering all cor...