I am trying to write a unit test for a service method (below) and I want to assert that the valued from the repo is not null. But I keep getting null and it is throwing the exception instead. I am not sure where my mistake could be so any help will be appreciated.
Here is the test:
@ExtendWith(MockitoExtension.class)
class BookingHistoryServiceImplTest {
@Mock
BookingHistoryRepository mockBookingHistoryRepository;
@Mock
UserRepository userRepository;
@Mock
PaymentRepository paymentRepository;
@Mock
BookingHistoryRepository bookingHistoryRepository;
BookingHistoryService bookingHistoryServiceToTest;
@Mock
AccommodationRepository accommodationRepository;
private BookingHistoryEntity testBookingHistoryEntity;
private AccommodationEntity testAccommodationEntity;
private UserEntity testUser;
@BeforeEach
void setUp() {
this.testUser = new UserEntity();
this.testUser.setPassword(TEST_USER_PASSWORD).setFirstName(TEST_USER_FIRST_NAME)
.setLastName(TEST_USER_LAST_NAME).setEmail(TEST_USER_EMAIL)
.setRoles(Set.of(new UserRoleEntity().setRole(UserRoleEnum.USER))).setPhoneNumber(TEST_USER_PHONE)
.setId(TEST_USER_ID);
// this.userRepository.save(this.testUser);
this.testAccommodationEntity = new AccommodationEntity();
this.testAccommodationEntity.setName(TEST_HOTEL)
.setType(new AccommodationTypeEntity().setType(AccommodationTypeEnum.HOTEL)).setCity(TEST_CITY)
.setAddress(TEST_ADDRESS).setPostalCode(TEST_PK).setImageUrl(TEST_IMAGE).setId(TEST_HOTEL_ID);
// this.accommodationRepository.save(this.testAccommodationEntity);
this.testBookingHistoryEntity = new BookingHistoryEntity();
this.testBookingHistoryEntity.setBookingTime(LocalDateTime.now()).setCancelled(true).setEmail(TEST_USER_EMAIL)
.setFirstName(TEST_USER_FIRST_NAME).setCancelledOn(LocalDateTime.now()).setCheckIn(TEST_VALID_CHECKIN)
.setCheckOut(TEST_VALID_CHECKOUT).setGuest(this.testUser).setLastName(TEST_USER_LAST_NAME)
.setProperty(this.testAccommodationEntity).setPayment(getPaymentEntity()).setId(1L);
}
In setUp I also have this which was lost in copy/paste
this.bookingHistoryServiceToTest = new BookingHistoryServiceImpl(this.bookingHistoryRepository, new ModelMapper());
@Test
void find_completed_booking_by_id_should_return_BookingHistoryEntity() {
Mockito.when(this.mockBookingHistoryRepository.findById(this.testBookingHistoryEntity.getId()))
.thenReturn(Optional.of(this.testBookingHistoryEntity));
SummaryBookingServiceModel byId = this.bookingHistoryServiceToTest.findById(TEST_BOOKING_HISTORY_ID);
System.out.println();
assertNotNull(byId);
assertEquals(TEST_BOOKING_HISTORY_ID, byId.getBookingId());
}
}
The Service:
@Override
public SummaryBookingServiceModel findCompletedBookingBy(Long id) {
BookingHistoryEntity bookingHistoryEntity = this.bookingHistoryRepository
.findById(id).orElseThrow(() -> new ObjectNotFoundException("Booking with id " id " not found!"));
return mapToServiceModel(bookingHistoryEntity);
}
Exception:
com.example.onlinehotelbookingsystem.web.exception.ObjectNotFoundException: Booking with id 1 not found!
at com.example.onlinehotelbookingsystem.service.impl.BookingHistoryServiceImpl.lambda$findById$4(BookingHistoryServiceImpl.java:119)
at java.base/java.util.Optional.orElseThrow(Optional.java:403)
at com.example.onlinehotelbookingsystem.service.impl.BookingHistoryServiceImpl.findById(BookingHistoryServiceImpl.java:119)
at com.example.onlinehotelbookingsystem.service.impl.BookingHistoryServiceImplTest.find_completed_booking_by_id_should_BookingEntity(BookingHistoryServiceImplTest.java:141)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
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$6(TestMethodTestDescriptor.java:210)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
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:96)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
CodePudding user response:
Update: you have 2 mocks for BookingHistoryRepository:
mockBookingHistoryRepository
bookingHistoryRepository
and you configured the 1st one, but injected into the serviceToTest the 2nd one. So you need to remove one of them. F.e. remove bookingHistoryRepository
and inject into the serviceToTest mockBookingHistoryRepository
And some notes:
- You should not mock the instance you are testing. You need to remove @Mock here
@Mock BookingHistoryService bookingHistoryServiceToTest
- You need to inject mocked repositories into the serviceToTest. Like this (or use any other way to set instance fields with mocks)
@InjectMock BookingHistoryService bookingHistoryServiceToTest