So my problem is in a Test, when I call the method to test it gives this error:
java.util.NoSuchElementException: No value present at java.base/java.util.Optional.get(Optional.java:143) at com.MD.Medicine.Services.SaveService.savePlans(SaveService.java:57) at com.MD.Medicine.Services.SaveServiceTest.testSavePlans_failPills(SaveServiceTest.java:99) at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
My test:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SaveServiceTest {
@MockBean
private MedsRepo medsRepo;
@MockBean
private PlansRepo plansRepo;
@MockBean
private PlanDayRepo planDayRepo;
@Autowired
private SaveService saveService;
@Test
void testSavePlans_failPills() {
LocalDate date = LocalDate.now();
Date date3 = new Date(1673740800000L);
Set<PlanDay> setPlans = new HashSet<>();
Plans plans = new Plans(1, setPlans);
BigDecimal price = new BigDecimal(8.00);
Meds meds = new Meds(1, "Brufen", price, "Pain", 200, date, setPlans);
when(medsRepo.getReferenceById(meds.getMedsId())).thenReturn(meds);
int pillNumber = meds.getPillNumber();
List<PlanDay> planList3 = new ArrayList<PlanDay>();
PlanDay planDay3 = new PlanDay(1, date3, "Tuesday", plans, meds, 50000);
planList3.add(planDay3);
String expected3 = saveService.savePlans(planList3);
assertThat(expected3).isEqualTo("Error: No piils available (Existing Pills: " pillNumber ")");
}
When it gets in * String expected3 = saveService.savePlans(planList3);* it stops and prints the error.
The method:
public String savePlans(List<PlanDay> plans) throws Error {
//long planIdVerify = plans.get(0).getPlanDaysId();
Date firstDate = plans.get(0).getPlanDate();
long todayMili = System.currentTimeMillis();
long dateLimitMili = firstDate.getTime() 604800000;
long planId = plans.get(0).getPlans().getPlanId();
Plans plansWithId = new Plans();
plansWithId.setPlanId(planId);
plansRepo.save(plansWithId);
for (int i = 0; i < plans.size(); i ) {
long planDateInMili = plans.get(i).getPlanDate().getTime();
//long planIdMultiVerify = plans.get(i).getPlanDaysId();
if (planDateInMili <= dateLimitMili && todayMili<planDateInMili ) {
PlanDay planDay = plans.get(i);
long medsId = planDay.getMeds().getMedsId();
int medsToTake = planDay.getMedsToTake();
int pillNumber = medsRepo.getReferenceById(medsId).getPillNumber();
int pillUpdate = pillNumber - medsToTake;
Meds updatePlanDay = medsRepo.findById(medsId).get();
if (pillUpdate > 0) {
updatePlanDay.setPillNumber(pillUpdate);
} else {
return "Error: No piils available (Existing Pills: " pillNumber ")";
}
planDayRepo.save(planDay);
} else {
return "Week time interval not correct/Invalid planId (only one plan can be saved)";
}
}
return "Saved Successfully";
}
and my entities:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "meds")
@JsonIgnoreProperties(value = { "days" })
public class Meds {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long medsId;
@Column
private String medsName;
@Column
private BigDecimal price;
@Column
private String category;
@Column
private int pillNumber;
@Column
@CreationTimestamp
private LocalDate medsDate;
@OneToMany(mappedBy = "meds", cascade = {CascadeType.REMOVE}, fetch = FetchType.LAZY)
@OnDelete(action = OnDeleteAction.CASCADE)
private Set<PlanDay> days = new HashSet<PlanDay>();
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "planDay")
@JsonIgnoreProperties(value = { "planDaysId" })
public class PlanDay {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long planDaysId;
@Column
private Date planDate;
@Column
private String weekday;
@ManyToOne
@JoinColumn(name = "planId", nullable = false)
private Plans plans;
@ManyToOne
@JoinColumn(name = "medsId", nullable = false)
private Meds meds;
@Column
private int medsToTake;
}
I have been looking for a solution and the orElse()
method was one of the options but I can't make it work.. What would be a solution for this problem?
Kind Regards.
CodePudding user response:
MedsRepo is a MockBean when you call medsRepo.findById(medsId)
it will return an empty optional because you have no when
for that method.
int pillNumber = medsRepo.getReferenceById(medsId).getPillNumber(); //extract the Meds as a variable and keep using this
int pillUpdate = pillNumber - medsToTake;
Meds updatePlanDay = medsRepo.findById(medsId).get(); //trying to get the same as you did above
Should be
Meds updatePlanDay = medsRepo.getReferenceById(medsId);
int pillNumber = updatePlanDay.getPillNumber();
int pillUpdate = pillNumber - medsToTake;
//Meds updatePlanDay = medsRepo.findById(medsId).get(); no longer needed
Also on a different note you should look into the difference between findById
and getReferenceById
and what happens when there is no Meds
with that medsId