Testing Architecture

Purpose: Comprehensive guide to testing strategy, approach, and execution in the StockEase project.

This document serves as the entry point for understanding how tests are organized, what’s covered, and how to run them locally or in CI/CD.


Table of Contents

  1. Quick Start: Running Tests Locally
  2. Test Overview
  3. Test Structure
  4. Navigation by Role
  5. Test Artifact Locations
  6. Related Documentation

Quick Start: Running Tests Locally

Prerequisites

  • JDK 17+
  • Maven 3.8+
  • Spring Boot 3.5.7

Run All Tests

cd backend
mvn clean test

Run Specific Test Class

mvn test -Dtest=AuthControllerTest

Run Tests with Coverage Report

mvn clean test jacoco:report
# Report generated at: backend/target/site/jacoco/index.html

Run Integration Tests Only

mvn test -Dgroups=integration

View Coverage in Browser

# After running tests with coverage
open backend/target/site/jacoco/index.html

Test Overview

Current State

  • Total Test Classes: 9
  • Total Test Methods: 65+ (including parameterized variants)
  • Framework: JUnit 5 (Jupiter)
  • Mocking: Mockito
  • Test Profiles: test (H2 in-memory database)
  • Coverage Target: 70%+ line coverage, 60%+ branch coverage

Test Categories

Category Count Type Framework
Unit Tests 2 Context bootstrap, core logic Spring Boot Test
Controller Slice Tests 7 REST endpoint testing @WebMvcTest
Total 9

Technology Stack

JUnit 5 (Jupiter)
β”œβ”€ Annotations: @Test, @BeforeEach, @ParameterizedTest
β”œβ”€ Assertions: org.junit.jupiter.api
└─ Extensions: JUnit 5 extension model

Mockito 4.x
β”œβ”€ @Mock: Field-level mocks
β”œβ”€ @InjectMocks: Auto-wiring mocks
β”œβ”€ ArgumentMatchers: any(), eq()
└─ Verification: when(), verify()

Spring Boot Test 3.5.7
β”œβ”€ @SpringBootTest: Full context
β”œβ”€ @WebMvcTest: Slice test for controllers
β”œβ”€ @MockitoBean: Spring-aware bean mocking
└─ MockMvc: HTTP client simulation

Spring Security Test
β”œβ”€ @WithMockUser: Mock authenticated users
β”œβ”€ SecurityMockMvcRequestPostProcessors: CSRF tokens, roles
└─ JWT utilities: JwtUtil mock chains

Test Structure

Directory Layout

backend/src/test/
β”œβ”€β”€ java/com/stocks/stockease/
β”‚   β”œβ”€β”€ config/test/
β”‚   β”‚   └── TestConfig.java                 # Shared test beans & security context
β”‚   β”œβ”€β”€ controller/
β”‚   β”‚   β”œβ”€β”€ AuthControllerTest.java         # Auth endpoint tests (unit)
β”‚   β”‚   β”œβ”€β”€ ProductControllerTest.java      # Product retrieval tests (@WebMvcTest)
β”‚   β”‚   β”œβ”€β”€ ProductCreateControllerTest.java    # POST /api/products (@WebMvcTest)
β”‚   β”‚   β”œβ”€β”€ ProductDeleteControllerTest.java    # DELETE tests (@WebMvcTest)
β”‚   β”‚   β”œβ”€β”€ ProductFetchControllerTest.java     # GET tests (@WebMvcTest)
β”‚   β”‚   β”œβ”€β”€ ProductInvalidUpdateControllerTest.java  # PUT validation (@WebMvcTest)
β”‚   β”‚   β”œβ”€β”€ ProductPaginationControllerTest.java    # Pagination tests (@WebMvcTest)
β”‚   β”‚   β”œβ”€β”€ ProductUpdateControllerTest.java        # PUT tests (@WebMvcTest)
β”‚   β”‚   └── AuthControllerTest.java                 # Auth tests (unit)
β”‚   └── StockEaseApplicationTests.java      # Context bootstrap test
β”‚
└── resources/
    └── application-test.properties         # H2 test database config

Test File Naming Convention

  • Pattern: {ClassName}Test.java (singular)
  • Examples: AuthControllerTest, ProductControllerTest
  • Rationale: Clear ownership, easy discovery, follows Maven Surefire defaults

πŸ‘¨β€πŸ’Ό Product Manager / Business Analyst

  • Start: Testing Strategy β€” understand goals and scope
  • Then: Test Matrix β€” see what’s covered by feature
  • Finally: Check CI reports in backend/target/surefire-reports/

πŸ‘¨β€πŸ’» Backend Developer

  • Start: Spring Slices β€” understand @WebMvcTest, mocking patterns
  • Then: Security Tests β€” understand JWT/role testing
  • Then: Test Data & Fixtures β€” mock setup
  • Practice: Run mvn clean test locally and explore backend/src/test/java/

πŸ‘¨β€πŸ’» Frontend Developer

  • Start: Coverage & Quality β€” understand backend test status
  • Then: Security Tests β€” understand auth token validation
  • Reference: Links to API contract tests (when available)

πŸ”§ DevOps / CI-CD Engineer

  • Start: CI Pipeline Tests β€” what runs in GitHub Actions
  • Then: Coverage & Quality β€” threshold gates
  • Finally: Check .github/workflows/ci-build.yml for test stage execution

πŸ§ͺ QA / Test Engineer

  • Start: Test Pyramid β€” understand test breakdown
  • Then: Coverage Matrix β€” see coverage by layer/feature
  • Then: Naming Conventions β€” understand test structure
  • Practice: Review test classes in backend/src/test/java/com/stocks/stockease/

Test Artifact Locations

Source Code

Path Purpose
backend/src/test/java/com/stocks/stockease/ All test classes
backend/src/test/java/com/stocks/stockease/controller/ REST endpoint tests
backend/src/test/java/com/stocks/stockease/config/test/ Shared test configuration
backend/src/test/resources/ Test data, properties files

Generated Reports (Post-Build)

Report Location Command
JUnit XML backend/target/surefire-reports/TEST-*.xml mvn test
JUnit Text backend/target/surefire-reports/*.txt mvn test
JaCoCo HTML backend/target/site/jacoco/index.html mvn test jacoco:report
Compiled Tests backend/target/test-classes/com/stocks/stockease/ mvn test-compile

CI/CD Pipeline

File Purpose Trigger
.github/workflows/ci-build.yml Full test + build pipeline Push to main / PR
Surefire Reports Archive Test results artifact After mvn test
JaCoCo Report Archive Coverage HTML artifact After mvn jacoco:report

Test Pyramid

                    β–²
                   β•±β”‚β•²
                  β•± β”‚ β•²              5% System/E2E
                β•±   β”‚   β•²            (Future: full-stack UI tests)
               ╱─────┼─────╲
              β•±      β”‚      β•²
             β•±       β”‚       β•²       25% Integration/Slice
            β•±        β”‚        β•²      (7 controller tests w/ @WebMvcTest)
           ╱─────────┼─────────╲
          β•±          β”‚          β•²
         β•±           β”‚           β•²  70% Unit
        β•±            β”‚            β•² (1 app context test, isolated mocks)
       ╱─────────────┴─────────────╲
      β•±                             β•²
     β•±___________Unit Tests___________β•²

Current Ratio: ~70% unit, ~25% slice/integration, ~5% system
Target Ratio: Same (balanced across layers)


Key Testing Patterns

Pattern 1: @WebMvcTest (Controller Slicing)

  • Used in: 7 controller test classes
  • What it does: Loads only the web layer + security config
  • Benefits: Fast execution, no database or service layer
  • Example: ProductControllerTest.java
@WebMvcTest(ProductController.class)
@ExtendWith(MockitoExtension.class)
public class ProductControllerTest {
    @Autowired private MockMvc mockMvc;
    @MockitoBean private ProductRepository productRepository;
    // Tests use: mockMvc.perform(get(...))
}

Pattern 2: @SpringBootTest (Full Context)

  • Used in: StockEaseApplicationTests.java
  • What it does: Loads full application context
  • Benefits: Tests real bean wiring, integration scenarios
  • Caution: Slower execution
@SpringBootTest
@ActiveProfiles("test")
class StockEaseApplicationTests {
    @Test
    void contextLoads() { /* Spring boots successfully */ }
}

Pattern 3: MockitoBean Auto-Wiring

  • Used in: All controller tests
  • What it does: Injects mocked beans into Spring context
  • Pattern: @MockitoBean private Repository repository;

Pattern 4: Parameterized Tests

  • Used in: ProductControllerTest, ProductCreateControllerTest
  • Framework: @ParameterizedTest with @CsvSource
  • Benefit: Test multiple scenarios with one method
@ParameterizedTest
@CsvSource({
    "adminUser, ADMIN",
    "regularUser, USER"
})
void testWithRoles(String username, String role) { }

Pattern 5: Test Configuration Inheritance

  • Class: TestConfig.java
  • Provides: Mock JwtUtil, mock UserDetailsService, pre-configured SecurityContext
  • Usage: @Import(TestConfig.class) in test classes

Quick Reference: Test Execution Flow

1. Local Development
   └─ mvn clean test
      β”œβ”€ Compiles tests
      β”œβ”€ Loads application-test.properties (H2 database)
      β”œβ”€ Runs 9 test classes
      β”œβ”€ Generates JUnit reports
      └─ Success βœ“

2. With Coverage
   └─ mvn clean test jacoco:report
      β”œβ”€ Runs all tests (as above)
      β”œβ”€ Instruments bytecode for coverage
      β”œβ”€ Generates HTML report
      └─ Open: backend/target/site/jacoco/index.html

3. CI/CD Pipeline (GitHub Actions)
   └─ git push main
      β”œβ”€ Triggers .github/workflows/ci-build.yml
      β”œβ”€ Runs mvn clean verify
      β”œβ”€ Publishes results to GitHub
      └─ Blocks merge if tests fail

Testing Topics

Testing Techniques

Quality & Metrics

Architecture Overview


Last Updated: October 31, 2025
Version: 1.0
Status: βœ… Ready for review

Back to Architecture Index