You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何Mock同一行的链式方法调用?Mock代码抛空指针异常求助

Fixing NullPointerException When Mocking Chained Method Calls

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.

Break down the chain and mock each level separately:

  1. Create a mock for the intermediate type: First, make a mock for whatever class getURL() returns (replace URL with your actual class name):

    URL urlMock = mock(URL.class);
    
  2. Stub the first method call: Tell your serviceMock to return the mocked URL when getURL() is invoked:

    when(serviceMock.getURL()).thenReturn(urlMock);
    
  3. Stub the final method call: Now you can safely stub getDomain() on the mocked URL:

    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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:12:47