Spock框架问题:存根调用callRealMethod()未抛出预期异常
callRealMethod() Not Throwing Expected Exception in Spock Let's break down your issues step by step:
1. Why callRealMethod() Isn't Throwing the Expected Exception
First, let's recall what callRealMethod() does: this method (from org.spockframework.mock.IMockInvocation) triggers the execution of the real underlying method of your class under test (CUT), rather than using stubbed logic. Since your standard output shows babbles bubbles babbles 2 gubbins bubbles 2, we know the real method is actually running—so the problem likely lies in one of these areas:
- The real method doesn't actually throw the exception you expect: Double-check the implementation of your CUT's method. Maybe it has a try/catch block that swallows the exception, or the conditions for throwing the exception aren't being met during the test.
- Incorrect mock/stub type: If you're using a
Mock()instead of aSpy(), you might run into unexpected behavior. SpockSpyis designed for partial mocking (stubbing some methods while calling real ones for others), whereasMockdefaults to returning dummy values unless explicitly told to call the real method. - Stubbing order or overrides: Ensure you haven't set up a stub that's overriding the
callRealMethod()directive. For example, if you first stub the method to return a value, then later try to call the real method, the earlier stub might take precedence depending on how you've structured your test.
2. Locating callRealMethod() in Spock's Documentation
You mentioned struggling to find the official Javadoc for this method—you're correct that it lives in org.spockframework.mock.IMockInvocation, with the signature:
java.lang.Object callRealMethod()
While it might be tricky to find in some third-party Javadoc indexes, the official Spock documentation covers this method in its mocking section (focus specifically on spy usage and real method invocation). Your locally generated Javadoc is a reliable source here, as it's directly built from the code you're working with.
内容的提问来源于stack exchange,提问作者mike rodent

