我正在try 为我的服务编写测试,其中一些测试没有通过描述抛出意外的异常类型,Expect:<;com.bestteam.urlshorter.exception.ItemNotFoundException>;但Was:<;java.util.IllegalFormatConversionException>;
@Test
public void testGetWhenLinkNotFoundThenThrowException() {
assertThrows(ItemNotFoundException.class, () -> {
linkService.get("shortLink");
});
verify(linkRepository, times(0)).save(link);
}
下面是这个GET方法
public LinkDto get(String shortLink) {
Link linkEntity = linkRepository.findById(shortLink).orElseThrow(() -> new ItemNotFoundException(Link.class, shortLink));
linkEntity.setOpenCount(
linkEntity.getOpenCount() + 1
);
linkRepository.save(linkEntity);
return linkMapper.toDto(linkEntity);
}
LinkMapper是一个自定义映射器
public LinkDto toDto(Link link) {
if (link == null) {
return null;
}
LinkDto linkDto = new LinkDto();
linkDto.setLink(link.getLink());
linkDto.setShortLink(link.getShortLink());
linkDto.setOpenCount(link.getOpenCount());
linkDto.setIsActive(link.getIsActive());
linkDto.setCreationDateTime(link.getCreationDateTime());
linkDto.setExpirationDateTime(link.getExpirationDateTime());
if (link.getUser() != null) {
linkDto.setUserId(link.getUser().getId());
}
return linkDto;
}
ItemNotFoundException异常
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ItemNotFoundException extends RuntimeException {
public static final String DEFAULT_MESSAGE = "Entity not found";
public ItemNotFoundException() {
super(DEFAULT_MESSAGE);
}
public ItemNotFoundException(String message) {
super(message);
}
public ItemNotFoundException(Class<?> entityClass, Long id) {
super(String.format("%s: {%s, id=%d}", DEFAULT_MESSAGE, entityClass.getSimpleName(), id));
}
public ItemNotFoundException(Class<?> entityClass, String id) {
super(String.format("%s: {%s, id=%d}", DEFAULT_MESSAGE, entityClass.getSimpleName(), id));
}
}
我try 使用AdviceController创建全局异常处理程序,但没有帮助