|
| 1 | +package com.baeldung.mockito.java8; |
| 2 | + |
| 3 | +import static org.junit.Assert.assertFalse; |
| 4 | +import static org.junit.Assert.assertTrue; |
| 5 | +import static org.mockito.Matchers.any; |
| 6 | +import static org.mockito.Mockito.when; |
| 7 | + |
| 8 | +import java.util.Optional; |
| 9 | +import java.util.stream.Stream; |
| 10 | + |
| 11 | +import org.junit.Before; |
| 12 | +import org.junit.Test; |
| 13 | +import org.mockito.InjectMocks; |
| 14 | +import org.mockito.Mock; |
| 15 | +import org.mockito.MockitoAnnotations; |
| 16 | + |
| 17 | +public class UnemploymentServiceImplUnitTest { |
| 18 | + @Mock |
| 19 | + private JobService jobService; |
| 20 | + |
| 21 | + @InjectMocks |
| 22 | + private UnemploymentServiceImpl unemploymentService; |
| 23 | + |
| 24 | + @Test |
| 25 | + public void givenReturnIsOfTypeOptional_whenMocked_thenValueIsEmpty() { |
| 26 | + Person person = new Person(); |
| 27 | + |
| 28 | + when(jobService.findCurrentJobPosition(any(Person.class))).thenReturn(Optional.empty()); |
| 29 | + |
| 30 | + assertTrue(unemploymentService.personIsEntitledToUnemploymentSupport(person)); |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + public void givenReturnIsOfTypeOptional_whenDefaultValueIsReturned_thenValueIsEmpty() { |
| 35 | + Person person = new Person(); |
| 36 | + |
| 37 | + // This will fail when Mockito 1 is used |
| 38 | + assertTrue(unemploymentService.personIsEntitledToUnemploymentSupport(person)); |
| 39 | + } |
| 40 | + |
| 41 | + @Test |
| 42 | + public void givenReturnIsOfTypeStream_whenMocked_thenValueIsEmpty() { |
| 43 | + Person person = new Person(); |
| 44 | + |
| 45 | + when(jobService.listJobs(any(Person.class))).thenReturn(Stream.empty()); |
| 46 | + |
| 47 | + assertFalse(unemploymentService.searchJob(person, "").isPresent()); |
| 48 | + } |
| 49 | + |
| 50 | + @Test |
| 51 | + public void givenReturnIsOfTypeStream_whenDefaultValueIsReturned_thenValueIsEmpty() { |
| 52 | + Person person = new Person(); |
| 53 | + |
| 54 | + // This will fail when Mockito 1 is used |
| 55 | + assertFalse(unemploymentService.searchJob(person, "").isPresent()); |
| 56 | + } |
| 57 | + |
| 58 | + @Before |
| 59 | + public void init() { |
| 60 | + MockitoAnnotations.initMocks(this); |
| 61 | + } |
| 62 | +} |
0 commit comments