JUnit for Spring Integration Activator with return type Message<?>

可紊 提交于 2019-12-11 19:50:03

问题


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.


回答1:


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.




回答2:


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;
}


来源:https://stackoverflow.com/questions/53735359/junit-for-spring-integration-activator-with-return-type-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!