Search code examples
javaspringtestingjhipsterkurento

How to not connect to service when testing with Spring?


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 ?


Solution

  • Thanks to the help of everyone here, I managed to solve this problem :

    • I created an interface of KurentoClient and implemented a proxy that call KurentoClient methods
    • My "normal" @Bean kurentoClient returns the implemented proxy
    • I writed a @TestConfiguration (UnitTestConfiguration) and added a @Bean with the same signature as the one crated above but this one returns mockito's mock(KurentoClient.class)
    • I created a class TestBase that every test class extends and which

    contains

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = MyApp.class)
    @ContextConfiguration(classes = UnitTestConfiguration.class)
    public class TestBase {
    }