簡體   English   中英

使用Spring測試時如何不連接到服務?

[英]How to not connect to service when testing with Spring?

我有一個使用JHipster構建的應用程序,其中包含幾個測試。 我創建了一個簡單的配置類,以實例化連接到外部服務的Bean,如下所示:

@Configuration
public class KurentoConfiguration {

    @Bean(name = "kurentoClient")
    public KurentoClient getKurentoClient(@Autowired ApplicationProperties applicationProperties) {
        return KurentoClient.create(applicationProperties.getKurento().getWsUrl());
    }
}

但是,您可能會猜到,該代碼在測試期間崩潰,因為外部服務未啟動,但此代碼在應用程序上下文加載期間仍在運行。

因此,我需要創建此bean的“無狀態”版本以在測試期間使用。

這是一個由於我的配置而導致測試失敗的簡單示例:

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

有什么解決方案可以使此bean在單元測試期間不高度依賴於外部服務?

您可以在測試中使用MockBean批注替換現有的bean:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Face2FaceApp.class)
public class LogsResourceIntTest {

    @MockBean
    private KurentoClient kurentoClient;

    private MockMvc restLogsMockMvc;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);

        LogsResource logsResource = new LogsResource();
        this.restLogsMockMvc = MockMvcBuilders
            .standaloneSetup(logsResource)
            .build();
        given(kurentoClient.someCall()).willReturn("mock");
    }
    ....
}

這是Spring Boot文檔: https : //docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-mocking -豆子

由於這里所有人的幫助,我設法解決了這個問題:

  • 我創建了KurentoClient的接口並實現了一個調用KurentoClient方法的代理
  • 我的“正常” @Bean kurentoClient返回實現的代理
  • 我寫了一個@TestConfiguration( UnitTestConfiguration )並添加了一個與上面創建的@Bean具有相同簽名的@Bean,但是這個返回了mock(KurentoClient.class)mock(KurentoClient.class)
  • 我創建了一個TestBase類,每個測試類都可以擴展該類,

包含

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM