调用未存根的方法时抛出 RuntimeException

Throw a RuntimeException when invoking an unstubbed method(调用未存根的方法时抛出 RuntimeException)
本文介绍了调用未存根的方法时抛出 RuntimeException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在使用 Mockito.我想在调用未存根的方法时抛出 RuntimeException.

I'm using Mockito. I want to throw a RuntimeException when an unstubbed method is called.

有什么办法吗?

推荐答案

您可以为模拟设置默认答案.所有未存根的方法都将使用此默认答案.

You can set a default answer for a mock. All methods that aren't stubbed will use this default answer.

public void testUnstubbedException() {
    // Create a mock with all methods throwing a RuntimeException by default
    SomeClass someClass = mock( SomeClass .class, new RuntimeExceptionAnswer() );

    doReturn(1).when(someClass).getId(); // Must use doReturn

    int id = someClass.getId(); // Will return 1

    someClass.unstubbedMethod(); // Will throw RuntimeException
}

public static class RuntimeExceptionAnswer implements Answer<Object> {

    public Object answer( InvocationOnMock invocation ) throws Throwable {
        throw new RuntimeException ( invocation.getMethod().getName() + " is not stubbed" );
    }

}

请注意,您不能when 与此功能一起使用,因为该方法在 when 之前调用(mockito when() 调用如何工作?),它会在之前抛出 RuntimeException模拟进入存根模式.

Note that you cannot use when with this functionality, since the method is called before when (How does mockito when() invocation work?) and it will throw a RuntimeException before the mock goes into stubbing mode.

因此,您必须使用 doReturn 才能使其工作.

Therefore, you must use doReturn for this to work.

这篇关于调用未存根的方法时抛出 RuntimeException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)