Skip to content

Conversation

@knutwannheden
Copy link
Contributor

@knutwannheden knutwannheden commented Dec 3, 2025

When migrating JMockit Expectations blocks to Mockito, variables declared inside the block that have the same names as variables later in the test method now stay accessible to the generated when() calls.

Changes

  • Modified SetupStatementsRewriter to skip setup statement extraction when there's a variable name conflict
  • Updated JMockitBlockRewriter to track and preserve setup statements within mock invocation groups
  • Added wrapStatementsInBlock() to wrap both setup statements and when() calls in the same block
  • Updated setupStatementVariableNameConflict test to reflect the corrected behavior
  • Added new test setupStatementVariableUsedInResultAndTestCode for issue Still Variable name conflict in JmockitToMockito #844

Before (broken)

{
    String res = "mockedValue";
}
when(config.getValue()).thenReturn(res);  // error: res not in scope

After (fixed)

{
    String res = "mockedValue";
    when(config.getValue()).thenReturn(res);
}

When migrating JMockit `Expectations` blocks to Mockito, variables declared inside the block that have the same names as variables later in the test method now stay accessible to the generated `when()` calls.

### Changes
- Modified `SetupStatementsRewriter` to skip setup statement extraction when there's a variable name conflict
- Updated `JMockitBlockRewriter` to track and preserve setup statements within mock invocation groups
- Added `wrapStatementsInBlock()` to wrap both setup statements and `when()` calls in the same block
- Updated `setupStatementVariableNameConflict` test to reflect the corrected behavior
- Added new test `setupStatementVariableUsedInResultAndTestCode` for issue #844

### Before (broken)
```java
{
    String res = "mockedValue";
}
when(config.getValue()).thenReturn(res);  // error: res not in scope
```

### After (fixed)
```java
{
    String res = "mockedValue";
    when(config.getValue()).thenReturn(res);
}
```

Fixes:
 - #844
Copy link
Member

@timtebeek timtebeek left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks a lot!

@github-project-automation github-project-automation bot moved this from In Progress to Ready to Review in OpenRewrite Dec 3, 2025
@timtebeek timtebeek merged commit fa95357 into main Dec 3, 2025
2 checks passed
@timtebeek timtebeek deleted the fix/844 branch December 3, 2025 15:19
@github-project-automation github-project-automation bot moved this from Ready to Review to Done in OpenRewrite Dec 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Still Variable name conflict in JmockitToMockito

3 participants