This guide shows how to integrate AI-powered testing tools with your existing K11 TechLab Selenium Java Test Automation Framework.
- Current Framework Analysis
- AI Tools Integration Strategy
- Local LLM Setup
- RAG Implementation
- Voice Integration
- Practical Implementation Examples
- CI/CD Integration
This framework already has excellent foundations for AI integration:
- Modular Architecture: Well-structured with separate layers for WebUI, API, and database testing
- Configuration Management:
ConfigurationLoader,PropertyUtilfor dynamic configuration - Base Classes:
BaseSeleniumTest,BaseWebServiceTestfor consistent test structure - Page Object Model: Implemented in
pageObjectspackage - Reporting: ExtentReports integration for detailed test reporting
- Wait Strategies: Comprehensive wait utilities in
SeleniumWaitclass - Driver Management: Thread-safe driver handling in
DriverManager
- Test Case Generation: From existing page objects and test patterns
- Dynamic Locator Suggestions: Based on page structure analysis
- Intelligent Wait Strategies: AI-recommended wait conditions
- Test Data Generation: Smart test data based on application context
- Failure Analysis: AI-powered root cause analysis from logs and screenshots
# Install Ollama
# Download from https://ollama.ai/download
# Pull a suitable model for code analysis
ollama pull llama3
ollama pull codellama:7b
ollama pull mistral:7b# Download LM Studio from https://lmstudio.ai/
# Recommended models:
# - CodeLlama 7B/13B for code understanding
# - Mistral 7B for general tasks
# - Llama 3 8B for balanced performanceCreate a new package for AI integration:
src/main/java/org/k11techlab/framework/ai/
├── llm/
│ ├── OllamaClient.java
│ ├── LMStudioClient.java
│ └── LLMInterface.java
├── rag/
│ ├── CodebaseIndexer.java
│ ├── DocumentRetriever.java
│ └── VectorStore.java
└── generators/
├── TestCaseGenerator.java
├── PageObjectGenerator.java
└── LocatorGenerator.java
<dependencies>
<!-- AI/ML Dependencies -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>9.8.0</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-common</artifactId>
<version>9.8.0</version>
</dependency>
<!-- HTTP Client for LLM API calls -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
<!-- JSON Processing -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
<!-- Vector Database (Optional - for advanced RAG) -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
</dependencies>// CodebaseIndexer.java - Index your test artifacts
public class CodebaseIndexer {
public void indexFrameworkArtifacts() {
// Index Page Objects
indexDirectory("src/main/java/org/k11techlab/framework/selenium/pageObjects/");
// Index Test Cases
indexDirectory("src/test/java/org/k11techlab/framework_unittests/");
// Index Configuration Files
indexDirectory("config/");
// Index Documentation
indexFile("README.md");
}
private void indexDirectory(String path) {
// Implementation for indexing Java files, extracting:
// - Class names and methods
// - Locators and selectors
// - Test patterns
// - Configuration properties
// - Comments and documentation
}
}// VoiceCommandProcessor.java
public class VoiceCommandProcessor {
public void processVoiceCommand(String command) {
// Parse voice commands like:
// "Generate test for login page"
// "Create page object for checkout"
// "Add wait for element visibility"
if (command.contains("generate test")) {
generateTestFromVoice(command);
} else if (command.contains("create page object")) {
generatePageObjectFromVoice(command);
}
}
private void generateTestFromVoice(String command) {
// Extract page/feature name from voice command
// Use RAG to find similar existing tests
// Generate new test using AI
}
}package org.k11techlab.framework.ai.generators;
public class TestCaseGenerator {
private final LLMInterface llmClient;
private final DocumentRetriever ragRetriever;
public String generateTestCase(String pageObjectClass, String testScenario) {
// 1. Retrieve similar test patterns from RAG
String context = ragRetriever.findSimilarTests(pageObjectClass);
// 2. Get page object structure
String pageObjectCode = ragRetriever.getPageObjectCode(pageObjectClass);
// 3. Generate prompt for LLM
String prompt = buildTestGenerationPrompt(context, pageObjectCode, testScenario);
// 4. Call LLM to generate test
return llmClient.generateResponse(prompt);
}
private String buildTestGenerationPrompt(String context, String pageObject, String scenario) {
return String.format("""
Based on the following existing test patterns and page object:
Existing Test Patterns:
%s
Page Object:
%s
Generate a TestNG test method for scenario: %s
Requirements:
- Extend BaseSeleniumTest
- Use proper wait strategies from SeleniumWait class
- Include appropriate assertions
- Follow the existing code style and patterns
- Add proper logging and error handling
""", context, pageObject, scenario);
}
}package org.k11techlab.framework.ai.generators;
public class LocatorGenerator {
public List<String> suggestLocators(String elementDescription, String pageSource) {
String prompt = String.format("""
Analyze this HTML page source and suggest the best locators for: %s
Page Source:
%s
Provide locators in priority order:
1. ID (if available)
2. CSS Selector (stable)
3. XPath (relative)
4. Data attributes
Consider maintainability and stability.
""", elementDescription, pageSource);
String aiResponse = llmClient.generateResponse(prompt);
return parseLocatorSuggestions(aiResponse);
}
}package org.k11techlab.framework.ai.generators;
public class WaitStrategyGenerator {
public String suggestWaitStrategy(String elementType, String userAction) {
// Analyze your existing SeleniumWait class patterns
String waitPatterns = ragRetriever.getWaitPatterns();
String prompt = String.format("""
Based on these existing wait patterns from SeleniumWait class:
%s
Suggest the best wait strategy for:
- Element Type: %s
- User Action: %s
Consider:
- Element loading behavior
- Network latency
- Dynamic content loading
- Existing framework wait utilities
""", waitPatterns, elementType, userAction);
return llmClient.generateResponse(prompt);
}
}package org.k11techlab.framework.ai.generators;
public class TestDataGenerator {
public Map<String, Object> generateTestData(String testType, String environment) {
// Use your existing configuration system
String configContext = getConfigurationContext();
String prompt = String.format("""
Generate realistic test data for:
- Test Type: %s
- Environment: %s
Configuration Context:
%s
Generate data that:
- Follows data validation rules
- Is environment-appropriate
- Covers edge cases
- Integrates with existing test data patterns
""", testType, environment, configContext);
String response = llmClient.generateResponse(prompt);
return parseTestData(response);
}
private String getConfigurationContext() {
// Read from your application.properties and test-config.properties
return ConfigurationManager.getBundle().getAllProperties();
}
}public class AIEnhancedBaseSeleniumTest extends BaseSeleniumTest {
protected TestCaseGenerator aiGenerator;
protected LocatorGenerator locatorGenerator;
@BeforeMethod
public void initializeAI() {
super.start();
this.aiGenerator = new TestCaseGenerator();
this.locatorGenerator = new LocatorGenerator();
}
protected List<String> getSmartLocators(String elementDescription) {
String pageSource = getDriver().getPageSource();
return locatorGenerator.suggestLocators(elementDescription, pageSource);
}
protected void generateSimilarTest(String scenario) {
String testCode = aiGenerator.generateTestCase(
this.getClass().getSimpleName(),
scenario
);
Log.info("AI Generated Test: " + testCode);
}
}package org.k11techlab.framework.ai.generators;
public class PageObjectGenerator {
public String generatePageObject(String url, String pageName) {
// 1. Navigate to page and capture DOM
WebDriver driver = DriverManager.getBrowser();
driver.get(url);
String pageSource = driver.getPageSource();
// 2. Analyze existing page object patterns
String patterns = ragRetriever.getPageObjectPatterns();
// 3. Generate page object using AI
String prompt = buildPageObjectPrompt(patterns, pageSource, pageName);
String generatedCode = llmClient.generateResponse(prompt);
// 4. Format and save
return formatPageObjectCode(generatedCode, pageName);
}
private String buildPageObjectPrompt(String patterns, String pageSource, String pageName) {
return String.format("""
Generate a Page Object class following these patterns:
Existing Patterns:
%s
Page Source:
%s
Requirements:
- Class name: %sPage
- Extend BaseTestPage
- Use WebElement annotations
- Include meaningful method names
- Add proper wait strategies
- Follow existing naming conventions
""", patterns, pageSource, pageName);
}
}package org.k11techlab.framework.ai.analysis;
public class FailureAnalyzer {
public String analyzeTestFailure(ITestResult result) {
// Collect failure context
String stackTrace = getStackTrace(result.getThrowable());
String screenshot = getScreenshotPath(result);
String logs = getTestLogs(result);
String pageSource = getCurrentPageSource();
// AI analysis prompt
String prompt = String.format("""
Analyze this test failure and provide recommendations:
Test: %s
Exception: %s
Stack Trace:
%s
Page State: %s
Provide:
1. Root cause analysis
2. Fix suggestions
3. Prevention strategies
4. Similar known issues
""", result.getMethod().getMethodName(),
result.getThrowable().getMessage(),
stackTrace, pageSource);
return llmClient.generateResponse(prompt);
}
}package org.k11techlab.framework.ai.optimization;
public class ConfigurationOptimizer {
public Properties optimizeConfiguration(TestExecutionMetrics metrics) {
String currentConfig = ConfigurationManager.getBundle().getAllProperties();
String prompt = String.format("""
Optimize test configuration based on execution metrics:
Current Configuration:
%s
Execution Metrics:
- Average test duration: %d ms
- Failure rate: %.2f%%
- Timeout occurrences: %d
- Browser startup time: %d ms
Suggest optimized values for:
- DefaultTimeout
- WaitPollTime
- retry.count
- selenium.screenshots settings
""", currentConfig,
metrics.getAverageDuration(),
metrics.getFailureRate(),
metrics.getTimeoutCount(),
metrics.getBrowserStartupTime());
return parseOptimizedConfig(llmClient.generateResponse(prompt));
}
}pipeline {
agent any
stages {
stage('AI Test Generation') {
steps {
script {
// Generate additional test cases using AI
sh 'java -cp target/classes:target/test-classes org.k11techlab.framework.ai.TestCaseGenerator'
}
}
}
stage('Execute Tests') {
steps {
script {
// Run your existing test suite
sh 'mvn clean test -Dsuite=smoke'
}
}
}
stage('AI Analysis') {
steps {
script {
// Analyze results with AI
sh 'java -cp target/classes org.k11techlab.framework.ai.FailureAnalyzer'
}
}
}
}
post {
always {
// Enhanced reporting with AI insights
publishHTML([
allowMissing: false,
alwaysLinkToLastBuild: true,
keepAll: true,
reportDir: 'test-output',
reportFiles: 'ai-enhanced-report.html',
reportName: 'AI Enhanced Test Report'
])
}
}
}// Example voice commands for your framework:
"Generate page object for Wikipedia search page"
→ Creates WikipediaSearchPage.java with elements and methods
"Create test for login with invalid credentials"
→ Generates test method in appropriate test class
"Add explicit wait for submit button clickable"
→ Suggests wait strategy code snippet
"Analyze last test failure"
→ Provides AI analysis of recent failure
"Optimize configuration for faster execution"
→ Suggests configuration improvements
"Generate test data for checkout workflow"
→ Creates realistic test data for e-commerce flows- Set up Ollama/LM Studio with appropriate models
- Create AI package structure in your framework
- Implement basic LLM client integration
- Test with simple code generation
- Index existing framework code and tests
- Implement document retrieval system
- Create context-aware prompt generation
- Test with existing page objects and tests
- Implement test case generator
- Create page object generator
- Add locator suggestion system
- Integrate with existing base classes
- Add failure analysis capabilities
- Implement configuration optimization
- Create voice command processing
- Enhance CI/CD integration
- Add comprehensive error handling
- Implement caching and performance optimization
- Create comprehensive documentation
- Add monitoring and metrics
- No Data Leakage: All processing happens locally
- Offline Capability: Works without internet connection
- Fast Processing: No API latency
- Cost Effective: No per-request charges
public class AISecurityManager {
public String sanitizeCodeForAI(String sourceCode) {
// Remove sensitive information before AI processing:
// - Database credentials
// - API keys
// - Personal data
// - Proprietary business logic
return cleanCode;
}
}-
Test Development Speed
- Time to create new page objects
- Test case generation time
- Locator identification speed
-
Test Quality Improvements
- Reduced flaky tests
- Better wait strategies
- Improved locator stability
-
Maintenance Efficiency
- Faster failure diagnosis
- Quicker configuration optimization
- Reduced debugging time
-
Team Productivity
- Reduced manual coding time
- Faster onboarding for new team members
- Improved test coverage
This AI integration will transform your existing framework into an intelligent testing assistant while preserving all your current investments and patterns. The modular approach ensures you can implement these features incrementally without disrupting your existing test suite.