Skip to content

Commit

Permalink
Fix Mockito.mockConstructionWithAnswer with more than 2 invocations (#…
Browse files Browse the repository at this point in the history
…2545)

If you build a mockConstructionWithAnswer with more than 1 additionalAnswers, there was a logic error
whereby the method would return the wrong value when making the second last invocation. It would
accidentally think it's at the end an only return the last answer, never returning the second
last answer when it should.

Co-authored-by: John Pyeatt <john.pyeatt@singlewire.com>
  • Loading branch information
jspyeatt and johnpyeatt committed Jan 18, 2022
1 parent 9e95f1a commit 5505941
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/main/java/org/mockito/Mockito.java
Expand Up @@ -2185,7 +2185,7 @@ public static <T> MockedConstruction<T> mockConstructionWithAnswer(
context -> {
if (context.getCount() == 1 || additionalAnswers.length == 0) {
return withSettings().defaultAnswer(defaultAnswer);
} else if (context.getCount() >= additionalAnswers.length) {
} else if (context.getCount() > additionalAnswers.length) {
return withSettings()
.defaultAnswer(additionalAnswers[additionalAnswers.length - 1]);
} else {
Expand Down
Expand Up @@ -57,6 +57,19 @@ public void testConstructionMockDefaultAnswerMultiple() {
}
}

/**
* Tests issue #2544
*/
@Test
public void testConstructionMockDefaultAnswerMultipleMoreThanTwo() {
try (MockedConstruction<Dummy> ignored = Mockito.mockConstructionWithAnswer(Dummy.class, invocation -> "bar", invocation -> "qux", invocation -> "baz")) {
assertEquals("bar", new Dummy().foo());
assertEquals("qux", new Dummy().foo());
assertEquals("baz", new Dummy().foo());
assertEquals("baz", new Dummy().foo());
}
}

@Test
public void testConstructionMockPrepared() {
try (MockedConstruction<Dummy> ignored = Mockito.mockConstruction(Dummy.class, (mock, context) -> when(mock.foo()).thenReturn("bar"))) {
Expand Down

0 comments on commit 5505941

Please sign in to comment.