Advanced Testing: Mock Objects, Test Suites & TDD

Overview

  • Course: ECM2414 – Software Development
  • Topic: Further Testing (Mock Objects, Test Suites, Test-Driven Development)
  • Session: T1: W5-L2
  • Instructor: Prof. Solomon Oyelere
  • Department: Computer Science, University of Exeter

Previous Lecture Recap

  • Unit tests: The how, what, and why
  • JUnit framework: Structure and implementation
  • JUnit assertions: Testing validation methods

Mock Objects

The Problem with Real Objects

Testing Dependencies

  • Often want to test a class through a method it provides
  • Difficult when object depends on other objects/system parts that are:
    • Hard to control
    • Hard to reason about
    • Unpredictable in behavior

Real-World Challenges

Testing becomes complex when dependencies have:

  • External system interactions
  • Database connections
  • Network communications
  • File system operations
  • User interface components

Mock Objects Definition

Mock Objects: Cheap placeholder objects that are predictable and allow testing of methods in the current class without external dependencies.

When to Use Mock Objects

Use mock objects when the real object:

  1. Has non-deterministic behavior

    • Random number generators
    • Time-dependent functions
    • Network responses
  2. Is difficult to set up

    • Complex initialization procedures
    • Database connections
    • External service dependencies
  3. Has behavior that is hard to trigger

    • Network errors
    • System failures
    • Edge cases in external systems
  4. Is slow

    • Database queries
    • File operations
    • Network requests
  5. Has (or is) a user interface

    • GUI components
    • Interactive elements
    • Display dependencies
  6. Does not yet exist

    • Future components
    • Third-party services
    • Unfinished dependencies

Implementing Mock Objects

3-Step Process

  1. Use an interface to describe the object
  2. Implement the interface for production code
  3. Implement the interface in a mock object for unit testing

Benefits of Interface-Based Design

  • Polymorphism: Same interface, different implementations
  • Testability: Easy to substitute mock for real object
  • Flexibility: Can create multiple mock implementations

Mock Objects Example: Checker System

Production Code

Interface Definition

public interface Environmental {
    public long getTime();
    public void playWavFile(String name); 
    // any other needed methods 
}

Production Class

import java.util.Calendar;
 
public class Checker {
    private Environmental env;
    
    public Checker(Environmental env) { 
        this.env = env; 
    } 
    
    /** After 5pm play a whistle to remind people to go home */
    public void reminder() {
        Calendar cal = Calendar.getInstance(); 
        cal.setTimeInMillis(env.getTime());
        int hour = cal.get(Calendar.HOUR_OF_DAY); 
        
        if (hour >= 17) { // 5:00 pm 
            env.playWavFile("quit_whistle.wav"); 
        }
    }
}

Mock Implementation

Mock Class with Control Methods

public class MockSystemEnvironmental implements Environmental { 
    private long currentTime;
    private boolean playedWav; 
    
    // Interface implementation
    public long getTime() { 
        return currentTime; 
    }
    
    public void playWavFile(String name) { 
        playedWav = true;
    }
    
    // Mock control methods (not in interface)
    public void setTime(long time) { 
        currentTime = time; 
    } 
    
    public void resetWav() { 
        playedWav = false; 
    } 
    
    public boolean wavWasPlayed() {
        return playedWav;  
    }
} 

Key Mock Features

  • Implements same interface as production code
  • Additional control methods (setTime(), resetWav()) for test manipulation
  • State tracking (wavWasPlayed()) for verification

Test Implementation

Test Setup

import java.util.Calendar;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
 
public class TestChecker { 
    private MockSystemEnvironment env; 
    private Calendar cal;
    private long t1; 
    
    @Before
    protected void setUp() {
        env = new MockSystemEnvironment(); 
        
        // Set up target test time
        cal = Calendar.getInstance(); 
        cal.set(Calendar.YEAR, 2011); 
        cal.set(Calendar.MONTH, 10); 
        cal.set(Calendar.DAY_OF_MONTH, 1); 
        cal.set(Calendar.HOUR_OF_DAY, 16); 
        cal.set(Calendar.MINUTE, 55);
        
        t1 = cal.getTimeInMillis(); 
    } 
    
    @After
    protected void tearDown() { 
        env = null; 
        cal = null; 
        t1 = 0; 
    } 
}

Test Cases

Test 1: Before 5 PM (Early)
@Test
public void testReminderEarly() { 
    env.setTime(t1);  // 4:55 PM
    Checker checker = new Checker(env); 
    
    checker.reminder(); 
    
    assertFalse(env.wavWasPlayed());  // Should not play wav
} 
Test 2: Exactly 5 PM (Boundary)
@Test
public void testReminderBoundary() { 
    t1 += (5 * 60 * 1000);  // Add 5 minutes → 5:00 PM
    env.setTime(t1);
    Checker checker = new Checker(env); 
    
    checker.reminder(); 
    
    assertTrue(env.wavWasPlayed());  // Should play wav
} 
Test 3: After 5 PM (Late)
@Test
public void testReminderLate() {
    t1 += (2 * 60 * 60 * 1000);  // Add 2 hours → 6:55 PM
    env.setTime(t1);
    Checker checker = new Checker(env); 
    
    checker.reminder(); 
    
    assertTrue(env.wavWasPlayed());  // Should play wav
}

Mock Objects Benefits

1. Predictable Behavior

  • Controlled responses to method calls
  • Deterministic test results
  • Repeatable test execution

2. Isolation Testing

  • Test single class without dependencies
  • No external system requirements
  • Fast test execution

3. Edge Case Testing

  • Simulate error conditions easily
  • Test boundary conditions precisely
  • Control timing and sequence

Test Suites

Purpose of Test Suites

  • Group multiple test classes to run as single batch
  • Run specific subset of unit tests from multiple test classes
  • Organized test execution for different scenarios

Basic Test Suite in JUnit 4

Simple Suite Implementation

import org.junit.runners.Suite; 
 
@RunWith(Suite.class) 
@Suite.SuiteClasses({TestAccount.class, TestBank.class}) 
public class TestSuite { 
    // Empty class - just holder for annotations
} 

Key Components

  • @RunWith(Suite.class): Specifies JUnit suite runner
  • @Suite.SuiteClasses({…}): Lists test classes to include
  • Empty class body: Class serves only as annotation holder

Categories in Test Suites

Category Marker Interfaces

public interface SmokeTests { /* category marker */ }
public interface SlowTests { /* category marker */ } 
public interface FastTests { /* category marker */ }

Test Classes with Categories

public static class A { 
    @Test 
    public void a() { fail(); }
    
    @Category(SlowTests.class)
    @Test
    public void b() { }
    
    @Category({FastTests.class, SmokeTests.class})
    @Test
    public void c() { }
}
 
@Category({SlowTests.class, FastTests.class})
public static class B {
    @Test
    public void d() { }
}

Category-Based Suite

@RunWith(Categories.class) 
@IncludeCategory(SlowTests.class) 
@SuiteClasses({A.class, B.class})
public static class SlowTestSuite { 
    // Runs: A.b, B.d
    // Does NOT run: A.a, A.c
} 

Suite Benefits

1. Organized Execution

  • Logical grouping of related tests
  • Batch execution of test classes
  • Consistent test running

2. Selective Testing

  • Category-based filtering for different scenarios
  • Smoke tests for quick validation
  • Slow tests for comprehensive checking

3. CI/CD Integration

  • Different suites for different pipeline stages
  • Fast feedback with quick test suites
  • Comprehensive testing with full suites

Test-Driven Development (TDD)

TDD Overview

Test-Driven Development: Development methodology where tests are written before production code.

TDD Benefits

1. Better Code Design

  • Forces good design decisions early
  • Loose coupling required for testability
  • Clear interfaces emerge naturally

2. User Perspective

  • See code from user’s perspective (not developer’s)
  • API design driven by usage patterns
  • Simpler, cleaner interfaces

3. Design Feedback

Example: If class is very difficult to test (e.g., functionality and GUI rolled into one), modify your design.

TDD Cycle

Red-Green-Refactor

  1. Red: Write failing test
  2. Green: Write minimal code to pass test
  3. Refactor: Improve code while keeping tests passing

Benefits of Cycle

  • Small increments reduce risk
  • Continuous validation of functionality
  • Immediate feedback on design decisions

Invariants

Definition

Invariants: Assertions about classes/objects that should not change - should definitely test these when developing unit tests.

Examples of Invariants

1. Array Implementation

// In a class implementing an array:
// - Array index >= 0
// - Array index < array length
assert index >= 0 && index < length;

2. Bank Account

// Credits and debits match the balance
assert credits - debits == balance;

3. Unit Conversions

// Measurements in different units should match after conversion
assert inchesToCm(inches) == inches * 2.54;

Invariant Testing Importance

1. Consistency Checking

  • Ensure object never viewed in inconsistent state
  • Validate business rules throughout object lifecycle
  • Catch logic errors early in development

2. Design Validation

  • Verify class contracts are maintained
  • Check assumptions about object state
  • Ensure correctness across method calls

Exercise: Mock Object Usage

Question: When should we consider using mock objects in testing?

All Options Are Correct

A. When the real object has non-deterministic behavior.

  • ✅ Correct: Mocks provide predictable responses

B. When the real object is difficult to set up.

  • ✅ Correct: Mocks eliminate complex initialization

C. When the real object has behavior that is hard to trigger.

  • ✅ Correct: Mocks can simulate error conditions easily

D. When the real object is slow to run.

  • ✅ Correct: Mocks provide fast test execution

E. When the real object has a user interface.

  • ✅ Correct: Mocks avoid GUI dependencies

F. When the real object does not yet exist.

  • ✅ Correct: Mocks enable development of dependent code

Key Takeaways

Mock Objects

  1. Enable isolated testing without external dependencies
  2. Provide predictable behavior for consistent test results
  3. Allow simulation of error conditions and edge cases
  4. Improve test performance by eliminating slow operations

Test Suites

  1. Organize test execution across multiple test classes
  2. Enable selective testing through categories
  3. Support CI/CD pipelines with different test phases
  4. Provide batch execution of related tests

Test-Driven Development

  1. Improves code design through testability requirements
  2. Provides user perspective on API design
  3. Catches design problems early in development
  4. Creates comprehensive test coverage naturally

Invariants

  1. Define object consistency requirements
  2. Validate business rules throughout execution
  3. Catch logic errors during development
  4. Ensure correctness of class implementations

Best Practices Summary

Mock Object Design

  • Use interfaces to enable easy mocking
  • Keep mocks simple and focused
  • Provide control methods for test manipulation
  • Track state changes for verification

Test Suite Organization

  • Group related tests logically
  • Use categories for different test types
  • Create fast suites for quick feedback
  • Maintain comprehensive suites for full validation

TDD Implementation

  • Write tests first to drive design
  • Keep tests simple and focused
  • Refactor regularly while maintaining passing tests
  • Use failure as design feedback

Next Topics

Module Schedule

  • Week 6: Reflective/reading week (No lectures or workshops)
  • Week 7:
    • L1: Further Testing (Mock Objects, Test Suites, Test-Driven Development)
    • L2: Design Patterns

Tags

java mockobjects testsuites tdd testdrivendevelopment junit unittesting invariants softwaretesting softwaredesign softwaredevelopment