Thread 类 PowerMockito 模拟 Thread.sleep 抛出中断异常的场景

发布时间 2023-03-27 11:59:18作者: 2一念轮回2
 

想要在单元测试时,模拟Thread.sleep()时抛出中断异常的行为,但是仅使用PowerMockito.mockStatic(Thread.class)是不够的,上代码:

要测试的方法getResult:

public class Weekend {   
     public void getResult() throws InterruptedException {
        try {Thread.sleep(2000);} 
        catch(InterruptedException e) { 
           throw e;     
       }   
     }
}     
@RunWith(PowerMockRunner.class)// 此处为实际执行 Thread.sleep()的类 Weekend.class,而不是 Thread.class
@PrepareForTest(Weekend.class)
 public class WeekendTest {   
        @InjectMocks    
        private Weekend weekend;   
 
        @Test(expected = InterruptedException.class)  
     public void testGetResult() throws InterruptedException {  
      PowerMockito.mockStatic(Thread.class); 
       PowerMockito.doThrow(new InterruptedException()).when(Thread.class);
       Thread.sleep(anyLong());   
        weekend.getResult();   
} }

需要注意的是,通常我们mock静态方法时,是在@PrepareForTest注解中,加上对应类名,如

@PrepareForTest(Utils.class)
public class Test {  
   public void testFunction() {   
   PowerMockito.mockStatic(Utils.class);    
   PowerMockito.when(Utils.function()).thenReturn(expectedResult);  
   }
}

但是对于Thread.sleep方法,在@PrepareForTest中加入Thread.class是无效的,必须加入实际调用Thread.sleep()方法的类,本例中为Weekend.class. 如果没有在@PrepareForTest中加入实际调用类,则无法抛出异常。

 

原文地址: https://blog.csdn.net/weixin_39576127/article/details/111110777