我正在尝试在下面对我的对象服务进行单元测试:
@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();
}
但是我收到一个错误:
No value present at java.util.Optional.get
当我尝试在下面实现我的 JUnit 时:@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));
}
}
有什么我错过的或我需要更新的吗?
最佳答案
您应该在这里做的第一件事是为 objectList
创建一个 stub 。 .
之后你会描述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);
}
Note 1: There is redundant(never used) object at the beginning of your test
Note 2: Notice usage of
Mockito.anyLong()
, which I think more appropriate in your case(for testingservice.getById();
)
关于java - 单元测试错误 : java. util.NoSuchElementException : No value present at java. util.Optional.get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50716941/