PowerMockito模拟静态方法抛出异常 [英] PowerMockito mock static method which throws exception

查看:3547
本文介绍了PowerMockito模拟静态方法抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些静态方法可以使用Mockito + PowerMock进行模拟.一切都是正确的,直到我尝试模拟仅引发异常的静态方法(并且什么也不做).

I have some static methods to mock using Mockito + PowerMock. Everything was correct until I tried to mock a static method which throws exception only (and do nothing else).

我的测试类如下:

顶部:

@RunWith(PowerMockRunner.class)
@PrepareForTest({Secure.class, User.class, StringUtils.class})

正文:

    PowerMockito.mockStatic(Secure.class);
    Mockito.when(Secure.getCurrentUser()).thenReturn(user);

    PowerMockito.mockStatic(StringUtils.class);
    Mockito.when(StringUtils.isNullOrEmpty("whatever")).thenReturn(true);

    PowerMockito.mockStatic(User.class);
    Mockito.when(User.findById(1L)).thenReturn(user); // exception !! ;(

    boolean actualResult = service.changePassword();

和changePassword方法是:

and changePassword method is:

  Long id = Secure.getCurrentUser().id;

  boolean is = StringUtils.isNullOrEmpty("whatever");

  User user = User.findById(1L);
  // ...

前两个静态调用工作正常(如果我注释掉第三个),但是最后一个(User.findById(long id))在"Mockito.when"方法中调用时引发异常.此方法如下所示:

The first 2 static calls works fine (if i comment out 3rd), but the last one ( User.findById(long id) ) throws exception while it is called in 'Mockito.when' method. This method looks like this:

 public static <T extends JPABase> T findById(Object id) {
        throw new UnsupportedOperationException("Please annotate your JPA model with @javax.persistence.Entity annotation.");
    }

我的问题是我该如何模拟此方法以获得预期的结果? 感谢您的帮助.

My question is how can i mock this method to get result as I expect ? Thanks for any help.

感谢所有回复.我找到了解决方案.我试图模拟一个方法findById,它不是直接在User.class中,而是在User扩展的GenericModel.class中.现在一切正常.

Thanks for all replies. I found a solution. I was trying to mock a method findById which was not directly in User.class but in GenericModel.class which User extends. Now everything works perfectly.

推荐答案

尝试更改此内容:

PowerMockito.mockStatic(User.class);
Mockito.when(User.findById(1L)).thenReturn(user);

对此:

PowerMockito.mockStatic(User.class);
PowerMockito.doReturn(user).when(User.class, "findById", Mockito.eq(1L));

在此处查看文档:

  • PowerMockitoStubber javadoc
  • PowerMockito Usage

这篇关于PowerMockito模拟静态方法抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆