I have an application built with JHipster which contains several tests. I created a simple configuration class that instantiate a bean connected to an external service as such :
@Configuration
public class KurentoConfiguration {
@Bean(name = "kurentoClient")
public KurentoClient getKurentoClient(@Autowired ApplicationProperties applicationProperties) {
return KurentoClient.create(applicationProperties.getKurento().getWsUrl());
}
}
But as you would guess, this code crash during testing because the external service is not up but this code is still run during application context loading.
So I need to create a "stateless" version of this bean to be used during testing.
Here is a simple example of a test that fail because of my configuration :
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Face2FaceApp.class)
public class LogsResourceIntTest {
private MockMvc restLogsMockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
LogsResource logsResource = new LogsResource();
this.restLogsMockMvc = MockMvcBuilders
.standaloneSetup(logsResource)
.build();
}
@Test
public void getAllLogs()throws Exception {
restLogsMockMvc.perform(get("/management/logs"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
}
}
What is the solution to make this bean not highly dependent of an external service during unit testing ?
Thanks to the help of everyone here, I managed to solve this problem :
UnitTestConfiguration
) and added a @Bean with the same signature as the one crated above but this one returns mockito's mock(KurentoClient.class)
TestBase
that every test class extends and which contains
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApp.class)
@ContextConfiguration(classes = UnitTestConfiguration.class)
public class TestBase {
}