Here's my setup which is not working:
SomeclassTest.java
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
@PrepareForTest({SomeclassTest.class, Someclass.class})
public class SomeclassTest{
@InjectMocks
private Someclass someclass;
@Test(expected=None.class)
public void testRun() throws Exception{
PowerMockito.mockStatic(Thread.class);
PowerMockito.doThrow(new RuntimeException()).when(Thread.class);
Thread.sleep(Matchers.anyLong());
try {
Thread.sleep(5L);
}catch(Exception ex) {
System.out.println("working"); // this is working
}
WhiteboxImpl.invokeMethod(someclass, "run"); // not working in someclass
PowerMockito.verifyStatic();
}
Someclass.java
@Named("Someclass")
public class Someclass extends Thread{
@Override
public void run() {
while (true) {
try {
// clear interruption
interrupted();
long noOfRec= 0;
if (noOfRec> 0) {
Thread.sleep(shortInterval);
} else {
Thread.sleep(longInterval);
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
} catch (Exception ex) {
}
}
}
My issue is PowerMockito isn't mocking Thread.sleep() when it's actually called in Someclass but weirdly working when Thread.sleep() is called inside the JUnit itself.
I am aware that wrapping Thread.sleep() in another method will solve my issue but I just want to know the correct method of mocking Thread.sleep() with PowerMockito.