单元测试错误:java.util.NoSuchElementException:java.util.Optional.get中没有值

时间:2018-06-06 09:33:19

标签: java spring junit mockito optional

我正在尝试在下面实现对象服务的单元测试:

@Service
public class ObjectServiceImpl implements ObjectService{

  private final ObjectDao objectDao;

  @Autowired
  public ObjectServiceImpl(ObjectDao objectDao){
    this.objectDao = objectDao;
  }

  @Override
    public Object getById(Long ObjectId) throws RecordNotFoundException {
        Optional<Object> Object = ObjectDao.findById(ObjectId);
        if (!Object.isPresent()) {
            throw new RecordNotFoundException(String.format(
                    MessageConstants.ObjectID_NOT_FOUND, ObjectId));
        }
        return Object.get(); 
    }

但是当我尝试在下面实现我的JUnit时出现错误:No value present at java.util.Optional.get

@RunWith(MockitoJUnitRunner.Silent.class)
public class ObjectServiceTest {

  @InjectMocks
  private ObjectServiceImpl objectServiceImpl;

  @Mock
  private ObjectDao objectDao;

  private ObjectService objectService;

   @Test
   public void getById() throws RecordNotFoundException{
     Object object = new Object();
    Long objectId = 1L;
    Optional<Object> objectList =
        objectDao.findById(objectId);
    given(objectDao.findById(
        objectList.get().getId())).willReturn(objectList); 
    objectServiceImpl.getById(Mockito.anyLong());
    Mockito.verify(objectDao).findById(objectId);
    assertNotNull(objectServiceImpl.getById(objectId));
  }


}

我有什么遗漏或需要更新吗?

2 个答案:

答案 0 :(得分:2)

这两个陈述不正确。

 Optional<Object> objectList =
        objectDao.findById(objectId);
 given(objectDao.findById(
        objectList.get().getId())).willReturn(objectList); 

首先,您尝试在mock(objectDao)上执行findById,然后在模拟调用此函数时需要返回的内容。

解决此问题的一种方法是

 @Test
   public void getById() throws RecordNotFoundException{
     Object object = new Object();
     Long objectId = 1L;
     Optional<Object> objectList = // create a object of Type Object manually and assign it 
     given(objectDao.findById(
        objectId)).willReturn(objectList); 
     Object returnedobject = objectServiceImpl.getById(objectId);
     Mockito.verify(objectDao).findById(objectId);
     assertNotNull(returnedobject);
  }

答案 1 :(得分:0)

这里你应该做的第一件事是为objectList创建一个存根。

之后,您将描述objectDao行为并执行验证。我的解决方案的变体是:

       @Test
       public void getById() throws RecordNotFoundException{
         // if it's List in your case
         Optional<Object> objectList = Optional.of(Arrays.asList(new YourType()));              
         given(objectDao.findById(Mockito.anyLong())).willReturn(objectList); 
         Object returnedObject = objectServiceImpl.getById(1L);
         Mockito.verify(objectDao).findById(Mockito.anyLong());
         assertNotNull(returnedObject);
      }
  

注1:在测试开始时有多余(从未使用过)的对象

     

注2:注意Mockito.anyLong()的使用情况,我认为在您的情况下更合适(用于测试service.getById();