简体   繁体   English

PowerMockito:检测到未完成的存根(未完成的存根异常)

[英]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. 当我尝试为上述功能编写jUnit测试用例时,将显示异常“ UnfinishedStubbingException”。

I read other answers, but even after that, I am unable to understand the reason for the error. 我阅读了其他答案,但是即使在那之后,我仍然无法理解错误的原因。

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. 您的问题是在通知PowerMockito应该模拟LocalDateTime静态方法之后,您正在运行LocalDateTime.of(2017, 8, 24, 8, 50, 9) 2017,8,24,8,50,9)方法。 So PowerMockito is trying to operate on mocked methods, while in the middle of a stubbing call. 因此,在存根调用期间,PowerMockito尝试对模拟方法进行操作。 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 . 进行此类操作的正确方法不是模拟LocalDateTime ,而是模拟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() . 您的Logic类应该具有您可以注入的Clock的实例,然后可以使用LocalDateTime.now(theClock)代替LocalDateTime.now() This makes the Logic class much more testable, because you can then inject your mock Clock . 这使Logic类更具可测试性,因为您可以随后注入模拟Clock

You don't actually need PowerMockito for this - ordinary Mockito will do just fine. 您实际上并不需要PowerMockito-普通的Mockito会很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM