0

I'm trying to test my method from service layer for getting all objects that exist, but I keep getting an error for my method .findAll() inside my Test class.

This is my Test class

@ExtendWith(MockitoExtension.class)
@SpringBootTest
public class UserServiceLayerTest {

    @Mock
    private ModelMapper modelMapper;

    @InjectMocks
    private UserServiceLayerImpl userService;

    @Mock
    private UserRepository userRepository;

    @Test
    public void findAllUsersTest() {
        // PREPARATION / STUB
        Mockito.when(userRepository.findAll()).thenReturn(Arrays.asList(
                new User("Billy", "Jones", "billy@gmail.com", "billyj123", "User"),
                new User("Hanna", "Taylor", "hannat@gmail.com", "hannaT", "User"),
                new User("Almighty", "Astro", "astroa@hotmail.com", "Astro33", "Admin")
        ));

        // ACTION
        List<UserDTO> allUsers = userService.findAll();

        // ASSERTION
        assertEquals(3, allUsers.size());
        assertEquals("Billy", allUsers.get(0).getFirstName());
        assertEquals("billy@gmail.com", allUsers.get(0).getEmail());
        assertEquals("Hanna", allUsers.get(1).getFirstName());
        assertEquals("hannat@gmail.com", allUsers.get(1).getEmail());
        assertEquals("Almighty", allUsers.get(2).getFirstName());
        assertEquals("astroa@hotmail.com", allUsers.get(2).getEmail());
    }```

This is my Service layer

@Service public class UserServiceLayerImpl implements UserServiceLayer {

@Autowired
private ModelMapper modelMapper;

@Autowired
private UserRepository userRepository;

@Override
public List<UserDTO> findAll() {
    return userRepository.findAll().stream()
            .map(user -> modelMapper.map(user, UserDTO.class)).collect(Collectors.toList());
}

}```

and this is my error:

java.lang.NullPointerException
    at com.ante.demo.heraprogram.servicetdd.UserServiceLayerTest.findAllUsersTest(UserServiceLayerTest.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)```


Now what do I need to do to fix this?
Ceki
  • 31
  • 1
  • 6
  • Have you debugged your code? Which variable is null? - it is not obvious from the stack trace. – Lesiak Mar 22 '22 at 19:47
  • Apparently I'm getting error on line `assertEquals(3, allUsers.size());` https://prnt.sc/LmVoJZB7tOv5 – Ceki Mar 22 '22 at 19:48

2 Answers2

1

You are missing the following:

  @BeforeEach
  void setUp() {

    MockitoAnnotations.openMocks(this);
  }

See this for more details: Initialising mock objects - MockIto

pringi
  • 3,987
  • 5
  • 35
  • 45
1

One thing that certainly causes NPE is that you use mock modelMapper, but you havent stubbed modelMapper.map. I would expect a list of three nulls as the result.

It is better to use a real ModelMapper, not a mock.

@ExtendWith(MockitoExtension.class)
public class UserServiceLayerTest {

    private ModelMapper modelMapper = new ModelMapper();

    @Mock
    private UserRepository userRepository;

    private UserServiceLayerImpl userService;

    @BeforeEach
    void setup() {
        userService = new UserSeviceLayerImpl(modelMapper, userRepository);
    }
}

Other comments:

  • you dont need SpringBootTest annotation
Lesiak
  • 22,088
  • 2
  • 41
  • 65
  • Yeah actually, I'm getting null https://prnt.sc/LmVoJZB7tOv5 – Ceki Mar 22 '22 at 19:56
  • you mean in void setup method for example? – Ceki Mar 22 '22 at 19:56
  • `@BeforeEach void setUp() { MockitoAnnotations.openMocks(this); }` like this? – Ceki Mar 22 '22 at 19:58
  • 1
    Nope, your MockitoExtension calls openMocks for you. I mean that you can construct `new ModelMapper` and pass it to your service (dont use @InjectMocks, construct the service manually. BeforeEach Setup method is a great place to do this. You may need to add a constructor to your service and use constructor injection instead of field injection) – Lesiak Mar 22 '22 at 20:02
  • for what exactly would I need a constructor in my service? also like this? `private ModelMapper modelMapper; private UserServiceLayerImpl userService; @Mock private UserRepository userRepository; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); modelMapper = new ModelMapper(); }` – Ceki Mar 22 '22 at 20:04
  • 1
    Almost. Again, you dont need openMocks if you use MockitoExtension. Then you need to pass modelMapper to your service, which is why you need a constructor in the service. See code in updated answer. – Lesiak Mar 22 '22 at 20:11
  • Okay what exactly here in my code was openMock? I edited code like you told me and it works, and I've no idea why, and tbh this is my first time testing. – Ceki Mar 22 '22 at 20:17
  • 1
    MockitoAnnotations.openMocks finds all fields in your test annotated with `@Mock` and initialises them to be mocks. Thus your repository is initialized in the test. MockitoExtension calls openMocks for you. – Lesiak Mar 22 '22 at 20:20
  • I think I understand it now. Thank you I'll check some more videos and documentation on junit 5 and mockito. Best regards – Ceki Mar 22 '22 at 20:27