Skip to content

MolemoMM/SimpleCalculator-unit-Testing-

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SimpleCalculator Unit Testing Project

This project demonstrates a simple Java calculator application with comprehensive unit testing using JUnit 5. It showcases best practices for unit testing, Maven project structure, and test-driven development.

Project Overview

The SimpleCalculator project implements basic arithmetic operations (addition and multiplication) with support for variable arguments (varargs). Each operation is thoroughly tested using JUnit 5 framework to ensure reliability and correctness.

Project Structure

SimpleCalculator-unit-Testing-/
├── pom.xml
└── src/
    ├── main/
    │   └── java/
    │       └── org/
    │           └── example/
    │               ├── Main.java
    │               └── SimpleCalculator.java
    └── test/
        └── java/
            └── org/
                └── example/
                    └── SimpleCalculatorTest.java

File Descriptions

  • pom.xml: Maven configuration file with JUnit 5 dependencies
  • SimpleCalculator.java: Main calculator class with arithmetic operations
  • Main.java: Application entry point (optional)
  • SimpleCalculatorTest.java: Comprehensive unit tests for calculator operations

Features

  • Addition: Supports adding multiple numbers using varargs
  • Multiplication: Supports multiplying multiple numbers using varargs
  • Comprehensive Testing: Full test coverage with edge cases
  • Maven Integration: Standard Maven project structure
  • JUnit 5: Modern testing framework with advanced assertions

Prerequisites

  • Java JDK 23 (as configured in pom.xml) or compatible version
  • Maven 3.6+ for build management
  • IDE (IntelliJ IDEA, Eclipse, or VS Code with Java extensions)

Setup Instructions

1. Environment Setup

Install Java JDK

# Check if Java is installed
java -version

# If not installed, download from:
# https://www.oracle.com/java/technologies/downloads/
# or use package manager like Chocolatey:
choco install openjdk

Install Maven

# Check if Maven is installed
mvn -version

# If not installed, download from:
# https://maven.apache.org/download.cgi
# or use Chocolatey:
choco install maven

2. Project Setup

# Clone or download the project
cd "c:\Users\mamas\OneDrive\Documents\wipro\SimpleCalculator-unit-Testing-"

# Download dependencies and compile
mvn clean compile

How to Run Tests

1. Running All Tests

# Run all tests
mvn test

# Run tests with detailed output
mvn test -Dtest.verbose=true

Expected Output:

[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running org.example.SimpleCalculatorTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS

2. Running Specific Test Methods

# Run specific test class
mvn test -Dtest=SimpleCalculatorTest

# Run specific test method
mvn test -Dtest=SimpleCalculatorTest#multipleNumbersShouldSumCorrectlyAdd

# Run multiple specific methods
mvn test -Dtest=SimpleCalculatorTest#multipleNumbersShouldSumCorrectlyAdd,multipleNumbersShouldSumCorrectlyMultiply

3. Test Report Generation

# Generate detailed test reports
mvn surefire-report:report

# View reports (generated in target/site/surefire-report.html)
start target\site\surefire-report.html

Understanding the Tests

Test Structure Analysis

The SimpleCalculatorTest.java contains two main test methods:

1. Addition Tests (multipleNumbersShouldSumCorrectlyAdd)

@Test
void multipleNumbersShouldSumCorrectlyAdd() {
    var calculator = new SimpleCalculator();
    
    // Test cases covered:
    assertEquals(3, calculator.add(1, 2));           // Basic addition
    assertEquals(-2, calculator.add(-1, -1));        // Negative numbers
    assertEquals(15, calculator.add(1, 2, 3, 4, 5)); // Multiple numbers
    assertEquals(4, calculator.add(-4, 8));          // Mixed positive/negative
}

Test Scenarios:

  • ✅ Two positive numbers
  • ✅ Two negative numbers
  • ✅ Multiple numbers (varargs)
  • ✅ Mixed positive and negative numbers

2. Multiplication Tests (multipleNumbersShouldSumCorrectlyMultiply)

@Test
void multipleNumbersShouldSumCorrectlyMultiply() {
    var calculator = new SimpleCalculator();
    
    // Test cases covered:
    assertEquals(3, calculator.multiply(1, 3));        // Basic multiplication
    assertEquals(-3, calculator.multiply(-1, 3));      // Negative numbers
    assertEquals(120, calculator.multiply(1, 2, 3, 4, 5)); // Multiple numbers
}

Test Scenarios:

  • ✅ Two positive numbers
  • ✅ Positive and negative numbers
  • ✅ Multiple numbers (factorial-like: 1×2×3×4×5 = 120)

Test Execution Flow

  1. Setup: JUnit creates a new test instance for each test method
  2. Execution: Each @Test method runs independently
  3. Assertion: assertEquals() compares expected vs actual results
  4. Reporting: Results are collected and reported by Maven Surefire

Development Workflow

1. Test-Driven Development (TDD)

# 1. Write a failing test first
# 2. Run tests to see it fail
mvn test

# 3. Implement minimal code to make test pass
# 4. Run tests again
mvn test

# 5. Refactor if needed
# 6. Repeat cycle

2. Adding New Features

Example: Adding Subtraction

Step 1: Add test method to SimpleCalculatorTest.java

@Test
void multipleNumbersShouldSubtractCorrectly() {
    var calculator = new SimpleCalculator();
    assertEquals(1, calculator.subtract(3, 2));
    assertEquals(-1, calculator.subtract(2, 3));
    assertEquals(0, calculator.subtract(5, 2, 3)); // 5-2-3=0
}

Step 2: Run test (should fail)

mvn test

Step 3: Implement method in SimpleCalculator.java

public int subtract(int... numbers) {
    if (numbers.length == 0) return 0;
    int result = numbers[0];
    for (int i = 1; i < numbers.length; i++) {
        result -= numbers[i];
    }
    return result;
}

Step 4: Run test again (should pass)

mvn test

Advanced Testing Techniques

1. Test Coverage Analysis

Add JaCoCo plugin to pom.xml:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.8</version>
    <executions>
        <execution>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
        </execution>
        <execution>
            <id>report</id>
            <phase>test</phase>
            <goals>
                <goal>report</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Run with coverage:

mvn clean test jacoco:report
# View coverage report: target/site/jacoco/index.html

2. Parameterized Tests

@ParameterizedTest
@ValueSource(ints = {1, 2, 3, 4, 5})
void additionWithSingleNumber(int number) {
    assertEquals(number, calculator.add(number));
}

3. Test Fixtures and Setup

class SimpleCalculatorTest {
    private SimpleCalculator calculator;
    
    @BeforeEach
    void setUp() {
        calculator = new SimpleCalculator();
    }
    
    @AfterEach
    void tearDown() {
        // Cleanup if needed
    }
}

Troubleshooting

Common Issues and Solutions

1. Tests Not Running

# Problem: Maven can't find tests
# Solution: Ensure proper directory structure
mvn clean compile test-compile test

2. JUnit Version Conflicts

# Problem: Multiple JUnit versions in pom.xml
# Solution: Clean up duplicate dependencies
mvn dependency:tree | findstr junit

3. Java Version Mismatch

# Problem: Compiler source/target mismatch
# Solution: Verify Java version matches pom.xml
java -version
mvn -version

4. Memory Issues During Testing

# Set Maven memory options
set MAVEN_OPTS=-Xmx1024m -XX:MaxPermSize=256m
mvn test

IDE Integration

IntelliJ IDEA

  1. Import as Maven project
  2. Right-click test class → "Run SimpleCalculatorTest"
  3. View test results in run window
  4. Generate coverage reports: Run → Run with Coverage

VS Code

  1. Install Java Extension Pack
  2. Open project folder
  3. Use Test Explorer to run tests
  4. View results in integrated terminal

Eclipse

  1. Import → Existing Maven Projects
  2. Right-click test class → Run As → JUnit Test
  3. View results in JUnit view

Best Practices Demonstrated

  1. Clear Test Names: Descriptive method names explaining what is being tested
  2. Multiple Assertions: Testing various scenarios in each test method
  3. Edge Cases: Testing with negative numbers, zero, and multiple parameters
  4. Isolation: Each test method is independent and can run alone
  5. AAA Pattern: Arrange (setup), Act (execute), Assert (verify)

Performance Testing

Benchmark Example

@Test
void performanceTest() {
    var calculator = new SimpleCalculator();
    long startTime = System.nanoTime();
    
    for (int i = 0; i < 1000000; i++) {
        calculator.add(1, 2, 3, 4, 5);
    }
    
    long duration = System.nanoTime() - startTime;
    assertTrue(duration < 1000000000); // Should complete in under 1 second
}

Author

  • Molemo Mamashela

Last updated: July 6, 2025

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages