I am trying to write a JUnit test cases. and I became clue less how can i write test case for the below method.
What all needs to be mocked.
@Autowired
private DoseService doseService;
public Message<List<Dose>> getAllDoses() {
log.info("GET method");
List<Dose> doseLst = doseService.getAllDoses();
return MessageBuilder.withPayload(doseLst).setHeader("http_statusCode",
HttpStatus.OK).build();
}
Thanks in advance for the help.
Looking to your method I would say that only DoseService
has to be mocked. Everything else looks good and you also don’t need the Message
as an argument.
For mocking you can use a @MockBean
from Spring Boot.
I wrote my test case like below and it works fine.
@Test
public void testGetAllDoses() {
List<Dose> doses = createDoses();
Message<List<Dose>> msg = MessageBuilder.withPayload(doses)
.setHeader("http_statusCode", HttpStatus.OK).build();
when(doseService.getAllDoses()).thenReturn(doses);
Message<List<Dose>> returned =doseServiceActivator.getAllDoses();
assertThat(returned.getPayload()).isEqualTo(msg.getPayload());
}
private List<Dose> createDoses(){
List<Dose> doses = new ArrayList<Dose>();
Dose dose1 = new Dose();
dose1.setDoseId(1);
dose1.setDoseValue("80");
Dose dose2 = new Dose();
dose2.setDoseId(2);
dose2.setDoseValue("120");
doses.add(dose1);
doses.add(dose2);
return doses;
}