Issue
I have the follow context on my Application. One Component is used for two services an these services are used it for a third service. I would like to test the integration between these services so I use @MockBean to mock the response from the Component. On the First service the mock works and I got a response, but on the second service I always got a null from the Component.
Here is my Application Context.
public class Service1 {
@Autowired
private Component component;
public Mono<String> getText() {
return component.getText()
.flatMap(string-> string.toUpperCase());
}
}
public class Service2 {
@Autowired
private Component component;
public Mono<String> getSubString() {
// always got null from component here
return component.getText()
.flatMap(string-> string.substring(1,2));
}
}
public class Service3 {
@Autowired
private Service1 service1;
@Autowired
private Service2 service2;
@Autowired
private Repository repository;
public Mono<String> getData() {
Mono<String> text1 = service1.getText();
Mono<String> subString = service2.getSubString();
return Mono.zip(text1, subString).flatMap( tuple -> {
return tuple.getT1(), tuple.getT2();
}).onSuccess(string-> repository.save(string));
}
}
@ActiveProfiles(profiles = "test")
@SpringBootTest(classes = {Application.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApplicationTest {
@MockBean
Component component;
@Autowired
Service3 service3;
@Autowired
Repository repository;
@Test
public testService3() {
given(component.getText()).willReturn("abc");
service.getData().subscribe();
assertNotNull(repository.findAll());
}
}
I tried to mock with theses ways:
given(component.getText()).willReturn("abc").willReturn("def");
or
given(component.getText()).willReturn("abc","def");
How can I get response from Component on service1 and service2 using the same @MockBean?
Solution
You should mock Service1
and Service2
, because Component
is dependency of them, not Service3
.
fix you code like this
@MockBean
Service1 service1;
@MockBean
Service2 service2;
//...
given(service1.getText()).willReturn("abc");
given(service2.getSubString()).willReturn("def");
Answered By - Kai-Sheng Yang
Answer Checked By - Katrina (JavaFixing Volunteer)