如何Mock同一行的链式方法调用?Mock代码抛空指针异常求助
Absolutely, you can mock chained method calls like this—you just need to account for each step in the chain. Here's why you're hitting that NullPointerException and how to fix it:
The problem right now is that when you write when(serviceMock.getURL().getDomain()).thenReturn(someDomainName);, Mockito hasn’t been told what serviceMock.getURL() should return. By default, mocked methods return null for object types, so serviceMock.getURL() gives you null, and calling .getDomain() on that null reference throws the NPE.
Solution 1: Explicitly Mock Each Intermediate Object (Recommended for Clarity)
Break down the chain and mock each level separately:
Create a mock for the intermediate type: First, make a mock for whatever class
getURL()returns (replaceURLwith your actual class name):URL urlMock = mock(URL.class);Stub the first method call: Tell your
serviceMockto return the mockedURLwhengetURL()is invoked:when(serviceMock.getURL()).thenReturn(urlMock);Stub the final method call: Now you can safely stub
getDomain()on the mockedURL:when(urlMock.getDomain()).thenReturn(someDomainName);
Putting it all together, your test setup will look like this:
// Initialize mocks Service serviceMock = mock(Service.class); URL urlMock = mock(URL.class); // Stub the chained calls when(serviceMock.getURL()).thenReturn(urlMock); when(urlMock.getDomain()).thenReturn("example.com"); // Test the call—no NPE now! String domain = serviceMock.getURL().getDomain(); assertEquals("example.com", domain);
Solution 2: Use Mockito's Deep Stubbing (Shorter, But Less Explicit)
If you’re using Mockito 1.9.5 or later, you can use deep stubs to handle the chain in one line:
Service serviceMock = mock(Service.class, RETURNS_DEEP_STUBS); when(serviceMock.getURL().getDomain()).thenReturn(someDomainName);
Just keep in mind that deep stubs can make tests harder to debug if something goes wrong, so the explicit approach is usually preferred for readability.
Either way, both methods will resolve your NullPointerException and let you successfully mock the chained method call.
内容的提问来源于stack exchange,提问作者sathvik vutukuri

