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

使用Mockito编写JUnit测试时遭遇NullPointerException问题求助

Hey there, let's figure out why you're hitting this NullPointerException when using Mockito with JUnit!

First, let's break down the error: the NPE is happening at line 57 in OrganizationServiceImpl.java when the findAll() method runs, triggered by your test method testGetAllOrganization at line 92. Most of the time, this boils down to a dependency in your service not being properly mocked or injected, leading to a null object when you try to use it.

Here are the most common causes and fixes:

1. Your Service's Dependencies Aren't Being Mocked/Injected

If your OrganizationServiceImpl relies on a repository (like OrganizationRepository) to fetch data, that dependency is probably null when the service runs.

Fix:

  • Use @Mock to create a mock instance of your repository in the test class.
  • Use @InjectMocks to automatically inject that mock into your service instance.
  • Make sure you initialize these annotations:
    • For JUnit 4: Add @RunWith(MockitoJUnitRunner.class) at the top of your test class.
    • For JUnit 5: Add @ExtendWith(MockitoExtension.class) instead.
    • Alternatively, call MockitoAnnotations.openMocks(this) in a @Before (JUnit4) or @BeforeEach (JUnit5) method to kick off Mockito's annotation processing.

2. You Forgot to Set a Return Value for Your Mocked Method

Even if you've mocked the repository, if you don't tell Mockito what to return when findAll() is called, it'll default to returning null. If your service tries to process that null value (like iterating over it), you'll get an NPE.

Fix:
In your test method, explicitly define the return value for the mocked repository method:

// Create a sample list of organizations to return
List<Organization> mockOrganizations = Arrays.asList(new Organization(), new Organization());
// Tell Mockito to return this list when the repository's findAll() is called
when(organizationRepository.findAll()).thenReturn(mockOrganizations);

3. You're Accidentally Using a Real Instance Instead of a Mock

If you instantiated your service with a real repository (not a mock), and that real repository isn't properly initialized (e.g., no database connection set up), it'll be null.

Fix:
Double-check that your service instance in the test is using the mocked repository, not a real one. The @InjectMocks annotation should handle this if you've set up @Mock correctly.

Quick Check: Look at Line 57 in Your Service

Take a peek at OrganizationServiceImpl.java line 57. Which object are you calling a method on? That's the one that's null. For example, if it's organizationRepository.findAll(), then organizationRepository is the null object—so focus on fixing how that repository is injected into the service.

Here's a quick example of a properly set up test class (JUnit 5):

@ExtendWith(MockitoExtension.class)
public class OrganizationServiceTest {

    @Mock
    private OrganizationRepository organizationRepository; // Mock the dependency

    @InjectMocks
    private OrganizationServiceImpl organizationService; // Inject mock into service

    @Test
    void testGetAllOrganization() {
        // Set up mock return value
        List<Organization> mockOrgs = List.of(new Organization(), new Organization());
        when(organizationRepository.findAll()).thenReturn(mockOrgs);

        // Execute the method under test
        List<Organization> result = organizationService.findAll();

        // Verify the result
        assertNotNull(result);
        assertEquals(2, result.size());
    }
}

Give these steps a try—chances are one of them will fix your NPE!

内容的提问来源于stack exchange,提问作者Aymen Kanzari

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:52:40