You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JUnit报错No value present或no such element,测试方法问题咨询

Fixing "No value present" / "No such element" Error in Your JUnit Test

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 an Optional without 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 Optional methods 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 return Optional.empty() and verify your service handles that scenario gracefully.

内容的提问来源于stack exchange,提问作者Rajat Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:30:21