$ python main.py analyze examples/UserService.javaOutput:
================================================================================
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()
$ python main.py generate examples/UserService.java --output UserServiceTest.javaOutput:
🔍 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
}$ python main.py generate examples/PaymentProcessor.java --quick-mocksOutput:
🔍 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;
============================================================
$ python main.py analyze examples/PaymentProcessor.java --verboseShows detailed information about:
- Each method's complexity
- Parameter types
- Exception types
- Dependencies used
- Suggested test strategies
Step 1: Analyze the code
python main.py analyze PaymentProcessor.java --verboseInsight: "🔴 processPayment() is complex (22 lines) - high priority for testing"
Step 2: Generate test class
python main.py generate PaymentProcessor.java -o PaymentProcessorTest.javaStep 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❌ No tests for UserService
❌ Don't know where to start
❌ Complex code, unclear dependencies
❌ Manual mock setup takes time
❌ Missed edge cases
✅ 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
- Read through code (30 min)
- Identify dependencies (15 min)
- Set up test class (10 min)
- Write @Mock annotations (10 min)
- Create test methods (60 min)
- Add assertions (30 min)
Total: ~2.5 hours
- Run analyze command (5 sec)
- Review analysis (5 min)
- Run generate command (5 sec)
- Customize tests (30 min)
Total: ~35 minutes
-
Always Analyze First
- Understand complexity before testing
- Identify high-risk areas (🔴 methods)
-
Start with Generated Tests
- Good foundation, not final product
- Customize for your specific logic
-
Use Quick Mocks
- Perfect for adding to existing tests
- Copy/paste into your test class
-
Focus on Complex Methods
- Methods marked 🔴 need most attention
- These are where bugs hide
-
Iterate
- Generate → Customize → Test → Repeat
# 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-mocksSee how easy testing legacy Java code can be! 🎉