java 抛出异常的 PowerMockito 模拟静态方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15520499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:55:14  来源:igfitidea点击:

PowerMockito mock static method which throws exception

javatestingmockingmockitopowermock

提问by elzix88

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).

我有一些静态方法可以使用 Mockito + PowerMock 进行模拟。一切都是正确的,直到我试图模拟一个只抛出异常的静态方法(不做其他任何事情)。

My test class looks like this:

我的测试类如下所示:

top:

最佳:

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

body:

身体:

    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();

and changePassword method is:

和 changePassword 方法是:

  Long id = Secure.getCurrentUser().id;

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

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

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:

前 2 个静态调用工作正常(如果我注释掉第 3 个),但最后一个( User.findById(long id) )在 'Mockito.when' 方法中调用时抛出异常。这个方法看起来像这样:

 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.

我的问题是如何模拟这种方法以获得预期的结果?谢谢你的帮助。



EDIT:

编辑:

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.

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

回答by Matt Lachman

Try changing this:

尝试改变这个:

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

To this:

对此:

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

See documentation here:

请参阅此处的文档: