Using GCP Secret Manager in integration tests in Java

Viewed 336

I have a pretty big code base written in Java. I have a lot of integration tests with both Kafka and Bigtable using JUnits ExternalResource. I have introduced fetching of secrets from GCP Secret Manager in my code. I now want to write integration tests for that as well.

So my scenario is that I want to create a mock username/password, create a secret of that username/password in my mock GCP Secret Manager, access the secrets and then use it to connect to my mock-service that requires that username/password. So, in reality, I'm connecting to a Kafka broker in my test with SSL and I want to simulate the entire flow with fetching of secrets.

The problem is, I can't find any documentation on how to do it. Google has great other documentation on how to emulate Bigtable, but I can't find any documentation on how to emulate/mock a Secret Manager. Has anyone ran into something similar?

2 Answers

In case you are using Spring Boot you may mock SecretManagerOperations interface using @TestConfiguration as follows:

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

}

Annotate the producer method with @Primary so that the mocked bean gets autowired during the test instead of the default implementation SecretManagerTemplate.

"GCP doesn't have any Emulator for Secret Manager" - @Guillaume Blaquiere.

Related