[英]Using GCP Secret Manager in integration tests in Java
我有一個相當大的代碼庫,用 Java 編寫。 我使用 JUnits ExternalResource 對 Kafka 和 Bigtable 進行了很多集成測試。 我已經在我的代碼中介紹了從 GCP Secret Manager 獲取機密。 我現在也想為此編寫集成測試。
所以我的場景是我想創建一個模擬用戶名/密碼,在我的模擬 GCP Secret Manager 中創建該用戶名/密碼的秘密,訪問秘密,然后使用它連接到需要該用戶名/密碼的模擬服務. 因此,實際上,我在測試中使用 SSL 連接到 Kafka 代理,並且我想通過獲取秘密來模擬整個流程。
問題是,我找不到任何有關如何操作的文檔。 谷歌有很多關於如何模擬 Bigtable 的其他文檔,但我找不到任何關於如何模擬/模擬 Secret Manager 的文檔。 有沒有人遇到過類似的事情?
“GCP 沒有任何 Secret Manager 模擬器” - @Guillaume Blaquiere。
如果您使用的是 Spring Boot,您可以使用@TestConfiguration
模擬SecretManagerOperations
接口,如下所示:
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.test.web.servlet.MockMvc;
import com.google.cloud.spring.secretmanager.SecretManagerOperations;
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MySecretIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testGettingSecretResource() throws Exception {
mockMvc.perform(get("/api/resource")).andExpect(status().isOk());
}
@TestConfiguration
public static class SecretManagerConfiguration {
@Bean
@Primary
public SecretManagerOperations secretManagerProducer() throws Exception{
SecretManagerOperations secretManager = mock(SecretManagerOperations.class);
when(secretManager.getSecretString("secret_id")).thenReturn("top secret");
return secretManager;
}
}
}
使用@Primary
注釋生產者方法,以便模擬 bean 在測試期間自動裝配,而不是默認實現SecretManagerTemplate
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.