Home > Mobile >  Testing DynamoDB: "Unable to load region from system settings"
Testing DynamoDB: "Unable to load region from system settings"

Time:08-18

I have a unit test that does nothing more than check if a bean exists.

    application.run( ( context ) -> {
        assertThat( context ).hasSingleBean( DynamoDbAsyncClient.class );
    } );

The code that creates the bean does the following:

@Bean
public DynamoDbAsyncClient dynamoDbAsyncClient()
{
    return DynamoDbAsyncClient.create();
}

This code cannot be changed!

If I run this test I get the following error: Unable to load region from system settings

So how can I specify a region for DynamoDB use? Can I mock some class for instance?

Thanks

CodePudding user response:

It looks like when you call DynamoDbAsyncClient.create(), the DynamoDbAsyncClient class loads the region from your DefaultAwsRegionProviderChain, which appears to be using your SystemSettingsRegionProvider to get it from your environment variables.

I'm pretty sure the error it's giving you is on line 37 of software.amazon.awssdk.regions.providers.SystemSettingsRegionProvider, which says:

return SdkClientException
    .builder()
    .message(
        String.format(
            "Unable to load region from system settings. Region"   " must be 
            specified either via environment variable (%s) or "   " system 
            property (%s).", 
            SdkSystemSetting.AWS_REGION.environmentVariable(), 
            SdkSystemSetting.AWS_REGION.property()
        )
    )
    .build();

So to answer your question:

So how can I specify a region for DynamoDB use? Can I mock some class for instance?

Yes, exactly: you mock the environment variable for AWS_REGION.

The easiest way to do this would be to use the library System Lambda, which has a method withEnvironmentVariables for setting environment variables.

You can use this analogously to the following:

import static com.github.stefanbirkner.systemlambda.SystemLambda.*;

public void EnvironmentVariablesTest {
  @Test
  public void setEnvironmentVariable() {
    String value = withEnvironmentVariable("name", "value")
      .execute(() -> System.getenv("name"));
    assertEquals("value", value);
  }
}

Hope that helps!

  • Related