带有时间依赖数据的单位测试没有PowerMock
我的班级有一种方法,该方法试图执行一些操作,并在完成所有操作后返回纳米时间。测试此方法时,我会遇到问题,测试结果总是不同的(因为取决于当前时间)。
如何正确测试返回值?没有Powermock有没有办法?
示例类:
class ExampleClass {
public long performOperationsAndGetTimeNano(){
//some operations...
return Instant.now().getNano();
}
...
}
示例测试:
@ExtendWith(MockitoExtension.class)
class ExampleTest{
private static final long EXPECTED_TIME = 555927900L;
private ExampleClass subject;
//init...
@Test
void performOperationAndGetTimeNano(){
long actualTime = subject.performOperationAndGetTimeNano(); //always different result
assertEquals(EXPECTED_TIME, actualTime); //always fails
}
}
感谢您的回答!
My class has a method, that tries to perform some operations and return nano time after all operations are completed. When testing this method I get a problem, that test result is always different (because depends on current time).
How to test return value correctly? Is there way without PowerMock?
Example class:
class ExampleClass {
public long performOperationsAndGetTimeNano(){
//some operations...
return Instant.now().getNano();
}
...
}
Example test:
@ExtendWith(MockitoExtension.class)
class ExampleTest{
private static final long EXPECTED_TIME = 555927900L;
private ExampleClass subject;
//init...
@Test
void performOperationAndGetTimeNano(){
long actualTime = subject.performOperationAndGetTimeNano(); //always different result
assertEquals(EXPECTED_TIME, actualTime); //always fails
}
}
Thanks for your answers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题:如何正确测试返回值?
fix: endiss_time = endured_time +(curtime_in_nanosec -endife_time),time Digit直到nano秒(偏移时间到当前nano secction secction secction secction xecreds_time)
实际_time = bucess.porformoperationandgetTimenano() - 这给出了时间数字直到nano seconds
private static final final long endive_time_time = getExpedlongTime();
在模拟的Java类中的Long GetExpedlongTime(){}方法,上面的类别在上面提供了预期_time。注意在Mockito中,每个输入数据都由具有示例输入数据的模拟Java类模拟。
B.没有Powermock有没有办法? 修复:是的,有上面的简单junit。不需要嘲笑的Java课,我们可以像A.一样编写单独的方法,并像上述一样使用
。希望我回答了您的两个问题。
Question: How to test return value correctly?
Fix: EXPECTED_TIME = EXPECTED_TIME + (CURTIME_IN_NANOSEC - EXPECTED_TIME), time digit till nano seconds(offset time till current nano second add to EXPECTED_TIME)
ACTUAL_TIME = subject.performOperationAndGetTimeNano()--This gives time digit till nano seconds
private static final long EXPECTED_TIME = getExpectedLongTime();
long getExpectedLongTime(){} method in mocked java class and used in above class gives EXPECTED_TIME as above. Note in Mockito, Every input data is mocked by Mock java class which has sample Input Data.
B. Is there way without PowerMock? Fix: Yes there is, Simple JUnit like above. No need for mocked java class, we can write seperate method and use like above as in A.
Hope I Answered both your questions.