我需要模拟一个ZonedDateTime.ofInstant()
方法。我知道 SO 中有很多建议,但是对于我的具体问题,直到现在我还没有找到任何简单的出路。
这是我的代码:
public ZonedDateTime myMethodToTest(){
MyClass myClass;
myClass = fetchSomethingFromDB();
try{
final ZoneId systemDefault = ZoneId.systemDefault();
return ZonedDateTime.ofInstant(myClass.getEndDt().toInstant(), systemDefault);
} catch(DateTimeException dte) {
return null;
}
}
这是我不完整的测试方法:
@Mock
MyClass mockMyClass;
@Test(expected = DateTimeException.class)
public void testmyMethodToTest_Exception() {
String error = "Error while parsing the effective end date";
doThrow(new DateTimeException(error)).when(--need to mock here---);
ZonedDateTime dateTime = mockMyClass.myMethodTotest();
}
我想ZonedDateTime.ofInstant()
在解析负面场景时模拟抛出 DateTimeException的方法。我怎么能做到这一点。
您不能Mockito
为此使用它,因为它ZonedDateTime
是一个最终类并且ofInstant
是一个静态方法,但您可以使用该PowerMock
库来增强Mockito
功能:
final String error = "Error while parsing the effective end date";
// Enable static mocking for all methods of a class
mockStatic(ZonedDateTime.class);
PowerMockito.doThrow(new DateTimeException(error).when(ZonedDateTime.ofInstant(Mockito.anyObject(), Mockito.anyObject()));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句