Sanchit Pruthi
Sanchit Pruthi

Reputation: 79

PowerMockito: Unfinished stubbing detected (Unfinished Stubbing Exception)

Logic

public class Logic {
String date = (LocalDateTime.now()).format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
}

Mock Code

@RunWith(PowerMockRunner.class)
@PrepareForTest({ LocalDateTime.class })
public class LogicTest {

@InjectMocks
Logic target = new Logic();

PowerMockito.mockStatic(LocalDateTime.class);
when(LocalDateTime.now()).thenReturn(LocalDateTime.of(2017, 8, 24, 8, 50, 9));

}

When I am trying to write the jUnit test case for the above function, an exception "UnfinishedStubbingException" is shown.

I read other answers, but even after that, I am unable to understand the reason for the error.

Upvotes: 1

Views: 895

Answers (1)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79807

Your problem is that you are running the method LocalDateTime.of(2017, 8, 24, 8, 50, 9) after you have informed PowerMockito that LocalDateTime static methods should be mocked. So PowerMockito is trying to operate on mocked methods, while in the middle of a stubbing call. You can't call one mocked method while you're in the middle of mocking another.

The correct way to do this kind of thing is not to mock LocalDateTime, but to mock Clock. Your Logic class should have an instance of Clock that you can inject, and you can then use LocalDateTime.now(theClock) instead of LocalDateTime.now(). This makes the Logic class much more testable, because you can then inject your mock Clock.

You don't actually need PowerMockito for this - ordinary Mockito will do just fine.

Upvotes: 2

Related Questions