I have the following service :
@Service
@RequiredArgsConstructor
public class LimitService {
private final CoreService coreService;
private final AuditService audit;
public Limit get(User user) {
Limit limit = coreService.get(user);
if (limit != null) {
Optional.ofNullable(limit.getAvailable())
.map(String::valueOf)
.map(BigDecimal::new)
.map(availableValue -> availableValue.setScale(2, RoundingMode.HALF_DOWN))
.map(BigDecimal::doubleValue)
.ifPresentOrElse(val -> limit.setAvailable(val), () -> limit.setAvailable(0d));
}
return limit;
}
}
and the following associated test
@ExtendWith(MockitoExtension.class)
public class LimitServiceTest {
@Mock
private CoreService coreService;
@Mock
private AuditService audit;
@InjectMocks
private LimitService service;
@BeforeEach
public void init(){
MockitoAnnotations.openMocks(this);
}
@Test
public void shouldReturnNull(){
assertThat(this.service.get(new User())).isNull();
}
@Test
public void shouldSetToZero_whenNull(){
User user = new User();
Mockito.when(this.coreService.get(any(User.class)))
.thenReturn(new Limit());
assertThat(this.service.get(user)).extracting(Limit::getAvailable)
.isEqualTo(0d);
}
}
When I run the second test in debug mode, I can see that a mock is actually generated for CoreService but Mockito seems to ignore the when..thenReturn.
I've also tried to use eq(user) instead of any(User.class), but the result is the same. I've a similar test in another project and everything works fine. I can't find out why this is not working in this case..