1

I have a class for my AWS Lambda handler, and it relies on environment variables for things like what region, bucket name, etc. For example:

public class SomethingCoolLambda {
  @NonNull private final String region = System.getenv("AWS_REGION");
  @NonNull private final String outputBucket = System.getenv("OUTPUT_BUCKET");

  public void eventHandler(@NonNull final ScheduledEvent event, @NonNull final Context context) {

      // Do cool stuff here, for example:

     final CoolQuery coolQuery =
        CoolQuery.builder()
            .targetBucket(outputBucket)
            .sqsClient(SqsClient.builder().region(Region.of(region)).build())
            .build();
  }
}
  

This works great. The problem is I'm writing an integration test and the test needs to use a different bucket instead of the live bucket.

Is there a way to instantiate or trigger SomethingCoolLambda() in a way where I can pass in an alternative bucket name instead of relying on the provided environment variable's value?

I want to avoid modifying the SomethingCoolLambda class, if possible.

Mark B
  • 183,023
  • 24
  • 297
  • 295
S.S.
  • 684
  • 8
  • 21
  • 1
    There's nothing really Lambda or AWS specific here. You just need to set that environment variable to a different value on your system that is running the unit test. If you want to do that in code, instead of in the script/command that you use to run your tests, then look at this: https://stackoverflow.com/questions/318239/how-do-i-set-environment-variables-from-java – Mark B May 26 '22 at 13:27
  • Good point, thanks for the link! I found the answer here: https://stackoverflow.com/questions/8168884/how-to-test-code-dependent-on-environment-variables-using-junit (was linked to in the link you provided) – S.S. May 26 '22 at 13:30
  • Does this answer your question? [How to test code dependent on environment variables using JUnit?](https://stackoverflow.com/questions/8168884/how-to-test-code-dependent-on-environment-variables-using-junit) – Ermiya Eskandary May 26 '22 at 13:48

1 Answers1

0

As Mark pointed out in his comment, my question isn't specific to AWS or Lambda.

If you want to set the value of environment variable specifically for testing, this post explains how to do it: How to test code dependent on environment variables using JUnit?

S.S.
  • 684
  • 8
  • 21