From 55059417fbba63c3c63cd7ab65aeb556424c967e Mon Sep 17 00:00:00 2001 From: John Pyeatt Date: Tue, 18 Jan 2022 10:36:00 -0600 Subject: [PATCH] Fix Mockito.mockConstructionWithAnswer with more than 2 invocations (#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 --- src/main/java/org/mockito/Mockito.java | 2 +- .../org/mockitoinline/ConstructionMockTest.java | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java index a0502a6eec..8c1a0cff9b 100644 --- a/src/main/java/org/mockito/Mockito.java +++ b/src/main/java/org/mockito/Mockito.java @@ -2185,7 +2185,7 @@ public static MockedConstruction 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 { diff --git a/subprojects/inline/src/test/java/org/mockitoinline/ConstructionMockTest.java b/subprojects/inline/src/test/java/org/mockitoinline/ConstructionMockTest.java index 4195080814..7eb87c5702 100644 --- a/subprojects/inline/src/test/java/org/mockitoinline/ConstructionMockTest.java +++ b/subprojects/inline/src/test/java/org/mockitoinline/ConstructionMockTest.java @@ -57,6 +57,19 @@ public void testConstructionMockDefaultAnswerMultiple() { } } + /** + * Tests issue #2544 + */ + @Test + public void testConstructionMockDefaultAnswerMultipleMoreThanTwo() { + try (MockedConstruction 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 ignored = Mockito.mockConstruction(Dummy.class, (mock, context) -> when(mock.foo()).thenReturn("bar"))) {