Back to Repositories

Validating URL Origin Construction in Stirling-PDF

This test suite validates URL utilities in the Stirling-PDF application, focusing on proper URL origin construction from HTTP requests. The test ensures correct assembly of URL components including scheme, server name, port, and context path.

Test Coverage Overview

The test coverage focuses on URL origin generation functionality within the UrlUtils class. Key test scenarios include:
  • Scheme validation (http)
  • Server name resolution
  • Port number handling
  • Context path integration
Integration points cover servlet request parameter extraction and URL string composition.

Implementation Analysis

The testing approach utilizes JUnit 5 with Mockito for HTTP request simulation. The implementation demonstrates clean mock object creation and explicit verification of URL component assembly. The test leverages Mockito’s when/then patterns for precise request attribute control.

Technical Details

Testing tools and configuration include:
  • JUnit Jupiter for test execution
  • Mockito framework for HTTP request mocking
  • Assert statements for result validation
  • Jakarta Servlet API integration

Best Practices Demonstrated

The test exhibits several quality practices:
  • Clear test method naming
  • Proper mock object setup
  • Isolated test scope
  • Explicit result verification
  • Clean separation of setup, execution, and verification phases

stirling-tools/stirling-pdf

src/test/java/stirling/software/SPDF/utils/UrlUtilsTest.java

            
package stirling.software.SPDF.utils;

import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class UrlUtilsTest {

    @Test
    void testGetOrigin() {
        // Mock HttpServletRequest
        HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
        Mockito.when(request.getScheme()).thenReturn("http");
        Mockito.when(request.getServerName()).thenReturn("localhost");
        Mockito.when(request.getServerPort()).thenReturn(8080);
        Mockito.when(request.getContextPath()).thenReturn("/myapp");

        // Call the method under test
        String origin = UrlUtils.getOrigin(request);

        // Assert the result
        assertEquals("http://localhost:8080/myapp", origin);
    }
}