Localstack AWS endpoint in application

Viewed 6659

I would like to run the functional tests for my application which tries to publish a message to AWS SNS. I tried LocalStack and found that it does everything I need to mock and publish messages locally. But my application uses amazon sdk client for java and when I run it locally it still tries to post requests to amazon region instead of the LocalStack

What is the configuration required to make sure that the application interacts with the local stack instead of the AWS URL? Can we specify the endpoint URL in AWS config? I found this to be a open issue in AWS CLI https://github.com/aws/aws-cli/issues/1270

Is there any workaround that anyone has implemented for this?

2 Answers

To use your localstack, you have to set your EndpointConfiguration.

AmazonSNS amazonSNS = AmazonSNSClientBuilder.standard()
  .withEndpointConfiguration(new EndpointConfiguration("http://localhost:4575", "eu-west-1")) 
  .build();

You should also use localstack/localstack instead of atlassian/localstack (no longer actively maintained).

If you're using JUnit 5 for the tests, let me recommend you JUnit 5 extensions for AWS, a few JUnit 5 extensions that could be useful for testing AWS-related code. These extensions can be used to inject clients for AWS service clients provided by tools like localstack (or the real ones). Both AWS Java SDK v 2.x and v 1.x are supported:

public static class Endpoint implements AWSEndpoint {
    @Override
    public String url() { return "http://localhost:4575"; }

    @Override
    public String region() { return "us-east-1"; }

    @Override
    public String accessKey() { return ""; }

    @Override
    public String secretKey() { return ""; }
}

@ExtendWith(SNS.class)
class AmazonDynamoDBInjectionTest {
    @AWSClient(endpoint = Endpoint.class)
    private AmazonSNS client;

    @Test
    void test() throws Exception {
        Assertions.assertNotNull(client);

        …
    }
}
Related