PowerMockito模拟Thread.sleep()时抛出中断异常的场景

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

要测试的方法getResult:

public class Weekend {

    public void getResult() throws InterruptedException {
        try {
            Thread.sleep(2000);
        } catch(InterruptedException e) {
            throw e;
        }
    }
}

WeekendTest文件

@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中加入实际调用类,则无法抛出异常。

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值