Reputation: 111
I have a test where an Optional was used. In the method, its stating no value was present. Here is the code, I have. How can I make this pass without NoSuchElementException.
public jobs theID(Integer id) {
if( id == null) {
throw new IllegalArgumentException("Its missing.");
}
return jobTitleMapper.entityToModel(this.jobTitleRepository.findById(id).get());
}
It is fussing about the get() from Java 8.
How do I use an Optional with isPresent correctly in this sense?
The test is:
public void findIdTest() {
Jobs jt = this.Service.theID(Entities.thisID);
Assert.assertNotNull(jt);
Assert.assertEquals(Entities.thisID, .getId());
}
Thanks for the help.
Upvotes: 9
Views: 76980
Reputation: 31
Must check Option YourObject.findById(id).isPresent()
exemple:
public YourObject getYourObject(Long id) {
if (id == null) {
return null;
}
return objectRepository.findById(id).isPresent() ?
objectRepository.findById(id).get(): null;
}
Upvotes: 2
Reputation: 673
That happens because the Optional returned by:
this.jobTitleRepository.findById(id)
can return an empty
, so if you call get() on it it will throw a java.util.NoSuchElementException
.
You can fix that with something like:
this.jobTitleRepository.findById(id).orElseGet(null)
or
this.jobTitleRepository.findById(id).orElseGet(new Jobs())
or fix the return Optional type in the original method: jobTitleRepository.findById(id)
Can you post this method jobTitleRepository.findById(id)
on your post aswell?
Upvotes: 6
Reputation: 2376
jobTitleRepository.findById(id)
it always returns an optional class so you don't need check if it is null, also before you call assertEquals()
you can check if object with passed id exists by calling someOptional.isPresent()
and if it's true you can make assert. But you should project your test cases to avoid mixing codintional statmens with asserations.
Upvotes: 0