JUnit报错No value present或no such element,测试方法问题咨询
Hey there, let's break down why you're running into that frustrating error in your testgetDictionaryValueListById test. The root issue is how you're mocking your repository call—here's what's going wrong and how to fix it:
The Problem
Your code tries to mock .get() directly on the result of dictionaryValueRepo.findById(1), like this:
Mockito.when(dictionaryValueRepo.findById(1).get()).thenReturn(dictionaryValue);
But findById() returns an Optional<DictionaryValue>, and at the time you call .get() in the when() method, Mockito hasn't mocked the findById() call yet. That means you're calling .get() on an empty Optional, which immediately throws the No value present exception you're seeing.
The Fix
Instead of mocking the .get() method, you need to mock findById() to return an Optional that contains your test dictionaryValue. Here's the corrected code:
// Mock the findById call to return an Optional containing your test object Mockito.when(dictionaryValueRepo.findById(1)).thenReturn(Optional.of(dictionaryValue)); // Now when your service calls findById(1).get(), it will work because the Optional isn't empty assertThat(dictionaryService.getDictionaryValueListById(1)) // Add your specific assertions here, e.g.: .isNotEmpty() .contains(dictionaryValue);
Extra Tips to Avoid This in the Future
- Never call
.get()on anOptionalwithout first checking if it's present (unless you're 100% sure it can't be empty, which isn't the case when setting up mocks!). - For safer production and test code, use
Optionalmethods like.orElseThrow()(if you expect the value to exist) or.orElse()(to provide a fallback) instead of raw.get(). - If you want to test the error case where the ID doesn't exist, mock
findById()to returnOptional.empty()and verify your service handles that scenario gracefully.
内容的提问来源于stack exchange,提问作者Rajat Gupta

