The main goal of this project is to explore basics od Mockito
in Spring Boot
environment.
-
add
@ExtendWith(MockitoExtension.class)
to the class -
mocking
-
no args
CustomerRepository customerRepository = mock(CustomerRepository.class); when(customerRepository.findAll()).thenReturn(Collections.singletonList(customer1));
-
regardless argument
CustomerRepository customerRepository = mock(CustomerRepository.class); when(customerRepository.findById(any(Integer.class))).thenReturn(Optional.of(customer1));
-
specific argument
CustomerRepository customerRepository = mock(CustomerRepository.class); when(customerRepository.findById(1)).thenReturn(Optional.of(customer1));
- Note that:
when(...).thenReturn(...)
anddoReturn(...).when(...)
are equivalent for mocks, they differ when comes to spy:- when thenReturn - makes a real method call just before the specified value will
be returned (if the called method throws an
Exception
you have to deal with it and you still get the result), - doReturn when - does not call the method at all.
- when thenReturn - makes a real method call just before the specified value will
be returned (if the called method throws an
-
-
to verify how many times method was invoked:
-
once (no args)
verify(customerRepository).findAll();
-
twice (specific argument)
verify(customerRepository, times(2)).findAll();
-
at least once (regardless argument)
verify(customerRepository, atLeast(1)).findById(any(Integer.class));
-
at most once
verify(customerRepository, atMost(1)).findById(2);
-
zero
verify(customerRepository, never()).findById(2);
-
Coverage: 70%