JUnit Testing Framework

Overview

  • Course: ECM2414 – Software Development
  • Topic: Testing with JUnit
  • Session: T1: W5-L1
  • Instructor: Dr. Wang Miao
  • Department: Computer Science, University of Exeter

Unit Testing Fundamentals

Definition

Unit Test: A piece of code written by a developer that exercises a small specific area of functionality of a class/method (in OO programming).

Purpose

  • Test the underlying hypothesis of the developer that code works as intended
  • Cannot prove code works completely, only that we haven’t disproved it works
  • Testing philosophy: Satisfy ourselves that code functions correctly under tested conditions

Importance of Unit Tests

1. Development Efficiency

  • Reduces time spent debugging
  • Faster bug identification and resolution
  • Immediate feedback during development

2. Code Documentation

  • Communicates intended use of code
  • Illustrates expected behavior on various inputs and conditions
  • Living documentation that stays updated with code

3. Code Quality Assurance

  • Prevents code drift from intended limits
  • Maintains consistency with design specifications
  • Regression prevention when making changes

Preparing Unit Tests

Step 1: Decide Testing Approach

  • Typically: Test a single method at a time
  • Focus: Some subset of functionality that method provides
  • Consider interactions with other methods and object attributes

Step 2: Setup Requirements

  • May need to “set up” instance prior to testing
  • Initialize object state as needed
  • Prepare test environment and dependencies

Step 3: Write Test Code

Critical timing: Write tests before implementation or concurrently, never afterwards

Step 4: Continuous Testing

  • Run unit tests as you develop the code
  • Ensure tests pass throughout development process
  • Fix failures immediately before adding new features

Planning Tests - Example

Given Method

static int largest(int[] list);

Test Cases to Consider

1. Ordering Tests

[7, 8, 9] → 9     // Ascending order
[8, 9, 7] → 9     // Mixed order  
[9, 7, 8] → 9     // Largest first

2. Duplicates

[7, 9, 8, 9] → 9  // Multiple occurrences of largest

3. Edge Cases

[1] → 1           // Single element
[-9, -8, -7] → -7 // All negative numbers

Right-BICEP Testing Framework

R - Right

Are the boundary results correct?

  • Verify results are “right” for expected inputs
  • Test normal operation scenarios

B - Boundary Conditions

Are all boundary conditions correct?

  • Edge values: minimum, maximum, empty, null
  • Array bounds: first, last, out-of-bounds
  • Numeric limits: zero, negative, overflow

I - Inverse Relationships

Can you check inverse relationships?

  • If function does X, can you verify by doing reverse of X?
  • Mathematical relationships: sqrt(x²) = x
  • Data transformations: serialize → deserialize = original

C - Cross-check

Can you cross-check results using other means?

  • Alternative algorithms for same problem
  • Known mathematical relationships
  • Independent calculations or references

E - Error Conditions

Can you force error conditions to occur?

  • Invalid inputs: null, wrong types, out-of-range
  • System failures: out of memory, file not found
  • Network issues: timeout, connection failure

P - Performance

Are performance characteristics within bounds?

  • Execution time limits
  • Memory usage constraints
  • Scalability requirements

Properties of Good Tests

1. Right-BICEP Compliant

All aspects of Right-BICEP framework addressed

2. Automatic

  • No manual intervention required
  • Automated execution and result verification
  • Integration with build systems

3. Thorough

  • Comprehensive coverage of functionality
  • Multiple test cases per method
  • Edge cases and normal cases covered

4. Repeatable

  • Same results every time
  • No dependency on external factors
  • Consistent environment setup

5. Independent

  • Independent of other tests (order doesn’t matter)
  • Independent of environment (OS, time, network)
  • Self-contained test data and setup

6. Professional

  • Same quality standard as production code
  • Well-structured and maintainable
  • Clear naming and documentation

Testing the Tests

1. Improve Tests While Fixing Bugs

  • Enhance test coverage based on discovered issues
  • Add regression tests for each bug found
  • Update tests when requirements change

2. Prove Tests by Introducing Bugs

Process:

  1. Intentionally break production code
  2. Verify test fails as expected
  3. Fix the code and ensure test passes
  4. Confirms test effectiveness

Purpose: Validate that test code detects the bugs it’s designed to catch

JUnit Framework Overview

Available Versions

  • JUnit 4: Focus of this module
  • JUnit 5: More recent version with enhanced features

Framework Components

JUnit 4 provides structured approach to unit testing in Java with:

  • Annotations for test methods
  • Assertion methods for verification
  • Setup/teardown lifecycle management
  • Test runners for execution

Structuring Unit Tests

Naming Conventions

Class and Method Naming

Pattern: If production class is Account with method createAccount:

// Production code
public class Account {
    public boolean createAccount(String name) { ... }
}
 
// Test code
public class AccountTest {
    @Test
    public void testCreateAccount() { ... }
    
    @Test  
    public void testCreateAccountDuplicates() { ... }
}

Rules

  • Test method names start with test
  • Multiple tests for same method allowed
  • Descriptive suffixes for different test scenarios

Test Method Structure

Basic Test Structure

@Test
public void testCreateAccount() {
    // 1. Setup - Create objects and set conditions
    Account acc = new Account();
    
    // 2. Execute - Call method under test
    boolean result = acc.createAccount("John");
    
    // 3. Verify - Check results
    assertTrue(result);
}

Complete Test Lifecycle

4-Step Process

  1. Set up all conditions needed for testing

    • Create required objects
    • Allocate needed resources
    • Initialize test data
  2. Call the method to be tested on the object

    • Execute actual functionality
    • Pass appropriate parameters
  3. Verify that object/class functions as expected

    • Use assertions to check results
    • Validate state changes
  4. Clean up after test

    • Release resources
    • Reset shared state

Test Organization

Test Class Structure

public class TestAccount {
    // Multiple tests for Account class
    @Test
    public void testCreateAccount() { ... }
    
    @Test
    public void testDeposit() { ... }
    
    @Test  
    public void testWithdraw() { ... }
    
    // Helper methods for setup
    private Account createValidAccount() { ... }
}

Execution Model

  • Test code imports testing framework classes
  • When executing tests: No need to run production code separately
  • Test code exercises production code automatically
  • Grouped by class: One test class per production class

JUnit Assertions

Purpose

Assertions are the fundamental building blocks of unit tests

  • Single test may have one to many assertions
  • Zero assertions still valid (using fail())

Basic Assertion Example

@Test
public void testDeposit() {
    Account acc = new Account();
    acc.deposit(100);
    
    assertEquals(100, acc.getBalance());    // Check balance
    assertTrue(acc.isActive());             // Check status
}

Exception Testing

@Test
public void testNullPointerException() {
    try { 
        foo.add(null);
        fail("Expected NullPointerException");  // Should not reach here
    } catch (NullPointerException e) { 
        // Expected behavior - test passes
    }
}

assertEquals Method

Basic Syntax

assertEquals(String msg, expected, actual)

Parameters

  • expected: Value you hope to see (typically literal)
  • actual: Value produced by code under test
  • msg: Optional message displayed if test fails

Example

assertEquals("Balance should be 100", 100, acc.getBalance());

Overloaded Versions

Multiple versions available for different data types:

assertEquals(int expected, int actual)
assertEquals(Object expected, Object actual)  
assertEquals(String expected, String actual)

Floating Point Assertions

The Problem

Floating point representation is not exact due to finite memory:

assertEquals(0.1 + 0.2, 0.3);  // FAILS! 
// Result: 0.30000000000000004

Solution: Tolerance-Based Comparison

assertEquals(String msg, expected, actual, tolerance)

Mathematical definition: |expected - actual| ≤ tolerance

Examples

// These assertions work correctly:
assertEquals(0.0012f, 0.0014f, 0.0002f);  // PASSES (difference = 0.0002)
assertEquals(0.0012f, 0.0014f, 0.0001f);  // FAILS (difference = 0.0002 > 0.0001)
 
// Proper way to test floating point arithmetic:
assertEquals(0.3, 0.1 + 0.2, 0.0001);

Additional Assertion Methods

Null Checking

assertNull(String msg, Object object)        // Object should be null
assertNotNull(String msg, Object object)     // Object should not be null

Reference Equality

assertSame(String msg, expected, actual)     // Same object reference
assertNotSame(String msg, expected, actual)  // Different object references

Boolean Conditions

assertTrue(String msg, boolean condition)    // Condition should be true
assertFalse(String msg, boolean condition)   // Condition should be false

Explicit Failure

fail(String msg)  // Immediately fail test with message

Use case: When code should not reach certain point (exception testing)

Testing Guidelines

Assertion Management

  • Multiple assertions per test are typical
  • First failure causes test to exit (remaining assertions not checked)
  • Fix failing code before continuing development

Bug Isolation

  • One or two tests fail when bug introduced → easier to locate
  • Focused failure points to specific problem area
  • Faster debugging through precise error location

Development Discipline

  • NEVER continue adding features while tests are failing
  • Fix tests immediately when they fail
  • Keep tests passing as features are added
  • Tests as safety net for ongoing development

JUnit 4 Setup

Required Imports

import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.*;

Annotations for Test Lifecycle

Method-Level Annotations

@Test           // Marks method as test case
@Before         // Runs before each test method
@After          // Runs after each test method

Class-Level Annotations

@BeforeClass    // Runs once before all tests in class
@AfterClass     // Runs once after all tests in class

Complete Example

public class AccountTest {
    private Account account;
    
    @BeforeClass
    public static void setUpClass() {
        // One-time setup for entire test class
    }
    
    @Before
    public void setUp() {
        // Setup before each individual test
        account = new Account();
    }
    
    @Test
    public void testDeposit() {
        account.deposit(100);
        assertEquals(100, account.getBalance());
    }
    
    @Test
    public void testWithdraw() {
        account.deposit(100);
        account.withdraw(50);
        assertEquals(50, account.getBalance());
    }
    
    @After
    public void tearDown() {
        // Cleanup after each test
        account = null;
    }
    
    @AfterClass
    public static void tearDownClass() {
        // One-time cleanup for entire test class
    }
}

Exercise: Right-BICEP Questions

Question: With Right-BICEP, what questions should you ask when preparing unit tests?

All Options Are Correct

A. Are the boundary results correct?

  • ✅ Right - Verify results are correct for expected scenarios

B. Are all boundary conditions correct? Are they identified correctly?

  • ✅ Boundary - Test edge cases, limits, extremes

C. Is the inverse relationship correct?

  • ✅ Inverse - Check mathematical/logical inverse operations

D. Can you cross-check the results using some other means?

  • ✅ Cross-check - Verify results through alternative methods

E. Are the error conditions correct?

  • ✅ Error - Force and test error scenarios

F. Are the performance characteristics within the performance bounds?

  • ✅ Performance - Validate timing and resource usage

Key Takeaways

Unit Testing Benefits

  1. Early bug detection reduces debugging time
  2. Code documentation through test examples
  3. Regression prevention during development
  4. Design validation of intended behavior

JUnit Framework Advantages

  1. Standardized structure for test organization
  2. Rich assertion library for result validation
  3. Lifecycle management with annotations
  4. IDE integration for easy execution

Best Practices

  1. Write tests early (before or during implementation)
  2. Follow Right-BICEP for comprehensive coverage
  3. Maintain test quality at production code standards
  4. Fix failures immediately before adding features

Migration Notes

JUnit 4 vs JUnit 5

For detailed differences between JUnit 4 and JUnit 5:

Key changes in JUnit 5:

  • New annotations (@Test → enhanced)
  • Lambda support for assertions
  • Dynamic tests capability
  • Enhanced parameterized tests

Next Topics

Upcoming lectures:

  • Mock objects for isolated testing
  • Test suites for organized test execution
  • Test-driven development (TDD) methodology

Tags

java junit unittesting tdd testdrivendevelopment assertions rightbicep softwaretesting qualityassurance softwaredevelopment