Reputation: 1377
I got this exception when mock the LocalDate.now()
static method with Mockito.mockStatic()
.
org.mockito.exceptions.misusing.UnfinishedStubbingException: Unfinished stubbing detected here: at utils.PowerMockTest.test(PowerMockTest.java:18)
E.g. thenReturn() may be missing.
Examples of correct stubbing: when(mock.isOk()).thenReturn(true); when(mock.isOk()).thenThrow(exception); doThrow(exception).when(mock).someVoidMethod(); Hints:
- missing thenReturn()
- you are trying to stub a final method, which is not supported
- you are stubbing the behaviour of another mock inside before 'thenReturn' instruction is completed
code is
public class MockStaticTest {
@Test
void test(){
LocalDate today=LocalDate.of(2020,11,20);
try (MockedStatic mocked = mockStatic(LocalDate.class)) {
mocked.when(LocalDate::now).thenReturn(LocalDate.of(2020,11,10));
Assertions.assertEquals(today,LocalDate.now());
mocked.verify(atLeastOnce(),LocalDate::now);
}
}
}
I'm a bit confused by the exception message because I certainly added thenReturn
statement.
Any help would be appreciated.
Upvotes: 7
Views: 4722
Reputation: 1761
You need to instantiate the return object outside of your try block.
The issue is that you are mocking the LocalDate
class, and then trying to use that same class within the mocked try
block;
mocked.when(LocalDate::now).thenReturn(LocalDate.of(2020,11,10));
@sankv answer works because it instantiates the returned LocalDate
prior to the static block.
Upvotes: 7
Reputation: 31
Try:
private LocalDate expectedReturn = LocalDate.of(2020, 11, 20);
@Test
void test() {
LocalDate today = LocalDate.of(2020, 11, 20);
try (MockedStatic<LocalDate> mocked = Mockito.mockStatic(LocalDate.class)) {
mocked.when(LocalDate::now).thenReturn(expectedReturn);
Assertions.assertEquals(today, LocalDate.now());
mocked.verify(Mockito.atLeastOnce(), LocalDate::now);
}
}
Upvotes: 3
Reputation: 100
did you try mocked.when(LocalDate.now()).thenReturn(LocalDate.of(2020,11,10)); ?
Upvotes: -2