RaveDash

java.util.NoSuchElementException: No value present - Error - Optional.get in JUNIT Testing with Spri

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.

2

3 Answers

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?

1

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; } 
1

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.

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJoa3JtZ26CdH2Oo5ivmV2qwaq4jKemrK2TnbKtscyepa2dqJiyscDIqKVmpp9iw6K41J5kqaqVqLKvwIyeqaunomK8scDIqKWapF2csrV5yKdko62e

Arica Deslauriers

Update: 2024-05-20