Skip to content

Latest commit

 

History

History
343 lines (268 loc) · 7.95 KB

File metadata and controls

343 lines (268 loc) · 7.95 KB

Java Mock Generator - Live Demo

🎬 See It In Action

Demo 1: Analyze Legacy Code

$ python main.py analyze examples/UserService.java

Output:

================================================================================
Java Mock Generator - Analysis Report
================================================================================

📦 Class: UserService
   Package: com.legacy.service

📊 Complexity Analysis
----------------------------------------
  Total methods: 7
  🟢 Simple:    1
  🟡 Moderate:  4
  🔴 Complex:   1
  Average lines per method: 9.4

🔗 Dependencies
----------------------------------------
  Total: 3
  Mockable: 3

  Fields to mock:
    • UserDAO userDAO
    • Connection dbConnection
    • Logger logger

✅ Testability
----------------------------------------
  Score: 80/100 - Good

  Issues:
    ⚠️  No constructor injection detected

💡 Test Coverage Suggestions
----------------------------------------
  • Write tests for 6 public methods
  • Test exception handling in 2 methods
  • Focus on 1 complex methods:
    - createUser() - 18 lines
  • Test edge cases for 3 validation/string methods

⚠️  Risk Areas
----------------------------------------
  • Database access detected - mock database calls
  • 2 methods throw exceptions - test error paths

🔧 Public Methods to Test
----------------------------------------
  🟡 User getUserById(int userId)
      throws: Exception
  🟡 List<User> getAllUsers()
  🔴 boolean createUser(String name, String email)
  🟡 void updateUserEmail(int userId, String newEmail)
      throws: Exception
  🟡 boolean deleteUser(int userId)
  🟢 int getUserCount()

Demo 2: Generate Test Class

$ python main.py generate examples/UserService.java --output UserServiceTest.java

Output:

🔍 Parsing examples/UserService.java...

✓ Test class generated successfully!
   Output: UserServiceTest.java

Next steps:
  1. Review the generated test class
  2. Customize mock behavior (when/thenReturn)
  3. Add specific assertions for your use cases
  4. Add edge cases and error scenarios

Generated Test (UserServiceTest.java):

/**
 * Auto-generated test class for UserService
 * Generated: 2025-11-16 14:17:22
 * 
 * This is a starting point - customize the tests as needed:
 * 1. Add actual assertions
 * 2. Set up mock behavior with when/thenReturn
 * 3. Add edge cases and error scenarios
 */
package com.legacy.test;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

import com.legacy.service.UserService;
import com.legacy.model.User;
import com.legacy.dao.UserDAO;

@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {

    // Mocked dependencies
    @Mock
    private UserDAO userDAO;

    @Mock
    private Connection dbConnection;

    // Class under test
    @InjectMocks
    private UserService userService;

    @Before
    public void setUp() {
        // Additional setup can go here
    }

    @Test
    public void testGetUserById_Success() {
        // Arrange
        int userId = 1;
        User mockUser = new User();
        when(userDAO.findById(userId)).thenReturn(mockUser);
        
        // Act
        User result = userService.getUserById(userId);
        
        // Assert
        assertNotNull(result);
    }

    @Test(expected = Exception.class)
    public void testGetUserById_ThrowsException() throws Exception {
        // Arrange - setup to trigger exception
        int userId = -1;
        
        // Act
        userService.getUserById(userId);
    }

    @Test
    public void testCreateUser_Success() {
        // Arrange
        String name = "John Doe";
        String email = "john@example.com";
        when(userDAO.insert(any())).thenReturn(1);
        
        // Act
        boolean result = userService.createUser(name, email);
        
        // Assert
        assertTrue(result);
    }
    
    // ... more tests generated
}

Demo 3: Quick Mocks Only

$ python main.py generate examples/PaymentProcessor.java --quick-mocks

Output:

🔍 Parsing examples/PaymentProcessor.java...

============================================================
Quick Mock Setup
============================================================
// Quick Mock Setup for PaymentProcessor
// Add these to your test class:

@Mock
private PaymentGateway paymentGateway;
@Mock
private CardValidator cardValidator;
@Mock
private NotificationService notificationService;
@Mock
private BigDecimal minimumAmount;

@InjectMocks
private PaymentProcessor paymentProcessor;
============================================================

Demo 4: Verbose Analysis

$ python main.py analyze examples/PaymentProcessor.java --verbose

Shows detailed information about:

  • Each method's complexity
  • Parameter types
  • Exception types
  • Dependencies used
  • Suggested test strategies

🎯 Real-World Usage

Scenario: Testing Legacy Payment System

Step 1: Analyze the code

python main.py analyze PaymentProcessor.java --verbose

Insight: "🔴 processPayment() is complex (22 lines) - high priority for testing"

Step 2: Generate test class

python main.py generate PaymentProcessor.java -o PaymentProcessorTest.java

Step 3: Customize the tests

@Test
public void testProcessPayment_Success() {
    // Arrange
    String cardNumber = "4532015112830366";
    BigDecimal amount = new BigDecimal("100.00");
    
    when(cardValidator.isValid(cardNumber)).thenReturn(true);
    when(paymentGateway.charge(any())).thenReturn(successResult);
    
    // Act
    PaymentResult result = processor.processPayment(cardNumber, amount, "USD");
    
    // Assert
    assertTrue(result.isSuccess());
    verify(notificationService).sendPaymentConfirmation(any(), eq(amount));
}

Step 4: Run and iterate

mvn test
# Fix issues, add more tests, repeat

📊 Before vs After

Before Using Tool

❌ No tests for UserService
❌ Don't know where to start
❌ Complex code, unclear dependencies
❌ Manual mock setup takes time
❌ Missed edge cases

After Using Tool

✅ Complete test scaffolding generated
✅ Clear analysis of what to test
✅ All mocks identified and set up
✅ Test methods for all public methods
✅ Exception handling covered
✅ Quick iteration on tests

🔄 Workflow Comparison

Manual Approach (Old Way)

  1. Read through code (30 min)
  2. Identify dependencies (15 min)
  3. Set up test class (10 min)
  4. Write @Mock annotations (10 min)
  5. Create test methods (60 min)
  6. Add assertions (30 min)

Total: ~2.5 hours

With Java Mock Generator (New Way)

  1. Run analyze command (5 sec)
  2. Review analysis (5 min)
  3. Run generate command (5 sec)
  4. Customize tests (30 min)

Total: ~35 minutes

💡 Pro Tips From Demo

  1. Always Analyze First

    • Understand complexity before testing
    • Identify high-risk areas (🔴 methods)
  2. Start with Generated Tests

    • Good foundation, not final product
    • Customize for your specific logic
  3. Use Quick Mocks

    • Perfect for adding to existing tests
    • Copy/paste into your test class
  4. Focus on Complex Methods

    • Methods marked 🔴 need most attention
    • These are where bugs hide
  5. Iterate

    • Generate → Customize → Test → Repeat

🎬 Try It Yourself!

# Clone or download the project
cd java-mock-generator

# Analyze the examples
python main.py analyze examples/UserService.java
python main.py analyze examples/PaymentProcessor.java

# Generate tests
python main.py generate examples/UserService.java -o test1.java
python main.py generate examples/PaymentProcessor.java -o test2.java

# Quick mocks
python main.py generate examples/UserService.java --quick-mocks

See how easy testing legacy Java code can be! 🎉