<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Testcontainers Archives - Codersee blog- Kotlin on the backend</title>
	<atom:link href="https://blog.codersee.com/tag/testcontainers/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>Kotlin &#38; Backend Tutorials - Learn Through Practice.</description>
	<lastBuildDate>Wed, 16 Apr 2025 04:49:36 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://blog.codersee.com/wp-content/uploads/2025/04/cropped-codersee_logo_circle_2-32x32.png</url>
	<title>Testcontainers Archives - Codersee blog- Kotlin on the backend</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Test Spring Boot AWS S3 with Localstack and Testcontainers</title>
		<link>https://blog.codersee.com/test-spring-boot-aws-s3-with-localstack-and-testcontainers/</link>
					<comments>https://blog.codersee.com/test-spring-boot-aws-s3-with-localstack-and-testcontainers/#respond</comments>
		
		<dc:creator><![CDATA[Piotr]]></dc:creator>
		<pubDate>Tue, 24 Sep 2024 05:00:00 +0000</pubDate>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[AWS]]></category>
		<category><![CDATA[LocalStack]]></category>
		<category><![CDATA[S3 Object Storage]]></category>
		<category><![CDATA[Testcontainers]]></category>
		<category><![CDATA[Testing]]></category>
		<guid isPermaLink="false">https://codersee.com/?p=12009164</guid>

					<description><![CDATA[<p>The last article in a series dedicated to Spring Boot AWS S3 integration focused on testing with LocalStack and Testcontainers.</p>
<p>The post <a href="https://blog.codersee.com/test-spring-boot-aws-s3-with-localstack-and-testcontainers/">Test Spring Boot AWS S3 with Localstack and Testcontainers</a> appeared first on <a href="https://blog.codersee.com">Codersee blog- Kotlin on the backend</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Welcome to the <strong>last article</strong> in a series dedicated to integrating a Spring Boot Kotlin app with <strong>AWS S3</strong> Object Storage, in which we will focus on <strong>integration testing with LocalStack and Testcontainers</strong>. And although we will focus on Object Storage, the approach we will use can be easily replicated with other AWS services.</p>



<p>I can guarantee that you will benefit from this tutorial regardless of whether you saw previous articles about S3Client or S3Template, or not. But, I definitely encourage you to take a look at them, too: </p>



<ul class="wp-block-list">
<li><a href="https://blog.codersee.com/spring-boot-aws-s3-s3client-kotlin/">#1 Spring Boot with AWS S3, S3Client, and Kotlin</a></li>



<li><a href="https://blog.codersee.com/spring-boot-with-kotlin-aws-s3-and-s3template/">#2 Spring Boot with Kotlin, AWS S3, and S3Template</a></li>



<li>#3 (This article)</li>
</ul>



<h2 class="wp-block-heading" id="h-video-tutorial">Video Tutorial</h2>



<p>If you prefer <strong>video content</strong>, then check out my video that covers all three articles:</p>



<div>
<a href="https://blog.codersee.com/test-spring-boot-aws-s3-with-localstack-and-testcontainers/"><img decoding="async" src="https://blog.codersee.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=%2F%2Fi.ytimg.com%2Fvi%2FuTV9w1JehHM%2Fhqdefault.jpg" alt="YouTube Video"></a><br /><br /></p></div>



<p>If you find this content useful,<strong> please leave a subscription</strong> 🙂</p>



<h2 class="wp-block-heading" id="h-prerequisites">Prerequisites</h2>



<p>Before heading to the guide, I just wanted to emphasize that today we will be working with <strong>Testcontainers</strong>. And this means that we must have a <strong>supported Docker environment</strong>.</p>



<p>So, if you do not have Docker configured on your local and want to follow this article, please check out <a href="https://java.testcontainers.org/supported_docker_environment/" target="_blank" rel="noreferrer noopener">their documentation</a>.</p>



<p>Of course, you must have Java, IDE, and Spring Boot project too, but I believe this is quite obvious 😉 </p>



<h2 class="wp-block-heading" id="h-testcontainers-and-localstack">Testcontainers and LocalStack</h2>



<p>Lastly, I would like to say a few words about the Testcontainers and LocalStack, which in my opinion are a great way to test Spring Boot S3 integration (and other AWS integrations, too). </p>



<h3 class="wp-block-heading" id="h-testcontainers">Testcontainers</h3>



<p><strong>Testcontainers </strong>is a library for providing throwaway, lightweight instances of Docker containers. They are an excellent approach whenever need to test behavior dependent on external services, like AWS, or some external databases. </p>



<p>Long story short, instead of mocking, or manual set up of some test environment, we define test dependencies as code. Then, we can run our test code and disposable containers will be started and deleted after they finish. </p>



<p>Let&#8217;s take a look at the example from <a href="https://docs.spring.io/spring-boot/reference/testing/testcontainers.html" target="_blank" rel="noreferrer noopener">Spring Boot docs</a>: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Testcontainers
@SpringBootTest
class MyIntegrationTests {

  @Test
  fun myTest() {
    // ...
  }

  companion object {
    @Container
    @JvmStatic
    val neo4j = Neo4jContainer("neo4j:5");
  }
}</pre>



<p>The above code runs a Neo4j docker container before the tests. Of course, this is just an example, so most of the time, we will need to add some more config. </p>



<p>Nevertheless, we can clearly see that this Testcontainers JUnit integration allows us to achieve our goal in an easy and neat manner. </p>



<h3 class="wp-block-heading" id="h-localstack">Localstack </h3>



<p><strong>Localstack</strong>, on the other hand, is a cloud service emulator that runs in a single container. In other words, we can run AWS applications or Lambdas <strong>without connecting to the remote cloud provider</strong>. </p>



<p>And thanks to the Testcontainers module for LocalStack, we can test various AWS integrations with just a few lines of code. </p>



<p>Again, let&#8217;s take a look at the example, but this time from the LocalStack documentation: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">DockerImageName localstackImage = DockerImageName.parse("localstack/localstack:3.5.0");

@Rule
public LocalStackContainer localstack = new LocalStackContainer(localstackImage)
        .withServices(S3);</pre>



<p>You will find links to both documentation at the end of this article. But for now, let&#8217;s not distract ourselves and focus on what we came here for 😉</p>



<h2 class="wp-block-heading" id="h-configure-project">Configure Project</h2>



<p>If you are following my S3 series, or you already have a Spring Boot project, then those are the necessary dependencies for us today: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">testImplementation("org.springframework.boot:spring-boot-starter-webflux")
testImplementation("org.testcontainers:localstack")
testImplementation("org.springframework.boot:spring-boot-testcontainers")</pre>



<p>As we can see, apart from LocalStack and TestContainers, we must provide the Spring Boot Starter WebFlux. </p>



<p>But why? </p>



<p>Well, this is necessary to work with WebTestClient- a client we will use to test our web servers (REST endpoints). </p>



<p>On the other hand, if you would like to set up a project from scratch, then please navigate to the <a href="https://start.spring.io/" target="_blank" rel="noreferrer noopener">Spring Initializr</a> and select the following:</p>



<figure class="wp-block-image aligncenter size-large"><img fetchpriority="high" decoding="async" width="1024" height="517" src="http://blog.codersee.com/wp-content/uploads/2024/09/codersee_integration_testing_spring_boot_aws_s3_spring_initializr_page-1024x517.png" alt="Image is a screenshot from Spring Initializr page and shows the settings necessary for integartion testing of Spring Boot and AWS S3 connection." class="wp-image-12009173" srcset="https://blog.codersee.com/wp-content/uploads/2024/09/codersee_integration_testing_spring_boot_aws_s3_spring_initializr_page-1024x517.png 1024w, https://blog.codersee.com/wp-content/uploads/2024/09/codersee_integration_testing_spring_boot_aws_s3_spring_initializr_page-300x151.png 300w, https://blog.codersee.com/wp-content/uploads/2024/09/codersee_integration_testing_spring_boot_aws_s3_spring_initializr_page-768x388.png 768w, https://blog.codersee.com/wp-content/uploads/2024/09/codersee_integration_testing_spring_boot_aws_s3_spring_initializr_page.png 1507w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>However, please keep in mind that LocalStack is not provided out of the box in Spring, so we must add it manually. </p>



<p>Moreover, as we have chosen the Spring Web, the WebFlux dependency is not present, too:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">testImplementation("org.springframework.boot:spring-boot-starter-webflux")
testImplementation("org.testcontainers:localstack")</pre>



<h2 class="wp-block-heading" id="h-testcontainers-singleton-approach">Testcontainers Singleton Approach</h2>



<p>With all of that being done, let&#8217;s head to the practice part. </p>



<p>When working with Testcontainers, we can configure them in various ways: </p>



<ul class="wp-block-list">
<li>we can use the<strong> JUnit extension</strong> (Jupiter integration)- which allows us to use <em>@Testcontainers</em> and <em>@Container</em> annotations and makes JUnit responsible for the automatic startup and stop of containers in our tests.</li>



<li>we can configure them <strong>manually </strong>in every test case, </li>



<li>or, alternatively, we can use the <strong>singleton approach</strong>&#8211; in which we control containers&#8217; lifecycle <a href="https://java.testcontainers.org/test_framework_integration/manual_lifecycle_control/" target="_blank" rel="noreferrer noopener">manually</a>. But, thanks to that we can easily reuse them across multiple test classes. </li>
</ul>



<p>Of course, these are not all approaches, and based on your needs you may want to configure Testcontainers differently. Nevertheless, in this tutorial, we will focus on the <strong>manual, reusable approach</strong>.</p>



<h3 class="wp-block-heading" id="h-introduce-base-class">Introduce Base Class</h3>



<p>Firstly, let&#8217;s introduce the <code>LocalStackIntegrationTest</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@SpringBootTest(webEnvironment = RANDOM_PORT)
class LocalStackIntegrationTest { }</pre>



<p>As we can see, we mark our class with <em>@SpringBootTest</em> &#8211; annotation necessary to run our integration tests and inject the instance of WebTestClient later in our subclasses. </p>



<h3 class="wp-block-heading" id="h-add-testcontainer">Add Testcontainer</h3>



<p>Following, let&#8217;s take a look at how to instantiate a LocalStack container:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">companion object {
  val localStack: LocalStackContainer = LocalStackContainer(
    DockerImageName.parse("localstack/localstack:3.7.2")
  )
}</pre>



<p>Right here, we create an instance of <strong>LocalStackContainer</strong> and we pass the name of a Docker image &#8211; <code>localstack/localstack:3.7.2</code>&#8211; to its constructor. Alternatively, if we are working only with AWS S3 Buckets service, then we can use a dedicated image- <code>localstack:s3-latest</code>. But personally, I am not a big fan of the <strong>latest</strong> tag, which can easily break our code.</p>



<p>Additionally, we put the LocalStackContainer instance in the <strong>companion object</strong>. Why? Because in the next steps, we will reference it in a function annotated with <em>@DynamicPropertySource</em>&#8211; and it must be static.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>Note related to <strong>JUnit extension</strong>: </p>



<p><br>This is not the case here, as we want to take care of the container lifecycle manually, but, when using the Jupiter integration, containers declared as static fields will be shared between test methods. They will be started only once before any test method is executed and stopped after the last test method has executed. So, if in your case you pick the JUnit extension and don&#8217;t want that to happen, then you must not put the localstack in the companion object. </p>
</blockquote>



<h3 class="wp-block-heading" id="h-control-testcontainer-lifecycle">Control Testcontainer lifecycle</h3>



<p>As we already know, with this approach <strong>we are responsible</strong> for the container lifecycle control. And although this may sound complicated, it basically means that without the extension we must start the container manually.</p>



<p>So the companion object after the update will look, as follows:  </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">companion object {
  val localStack: LocalStackContainer = LocalStackContainer(
    DockerImageName.parse("localstack/localstack:3.7.2")
  ).apply {
    start()
  }
}</pre>



<p>Basically, we use the Kotlin scope function (you can learn more about it in my <a href="https://codersee.com/the-complete-kotlin-course/">Kotlin course</a>) to invoke the <code>start()</code> function on the <code>localStack</code> instance. And as the name suggests, this function will start the container (and pull the image, if necessary).</p>



<p>And basically,<strong> that is all we need to do here.</strong> With the above code, the container will be started when the base class is loaded and shared across all inheriting test classes. </p>



<p>Of course, there is also the <code>stop()</code> function that we can invoke to kill and remove the container. </p>



<p>Nevertheless, <strong>we do not have to do it</strong>. Why? Let&#8217;s figure out. </p>



<h3 class="wp-block-heading" id="h-ryuk">Ryuk</h3>



<p>Ryuk is a kind of &#8220;garbage collector&#8221; in Testcontainers. </p>



<p>Whenever we run integration tests, Testcontianers core starts <strong>one more container</strong>: </p>



<figure class="wp-block-image size-full"><img decoding="async" width="756" height="188" src="http://blog.codersee.com/wp-content/uploads/2024/09/image.png" alt="Image is a screenshot from Docker Desktop and presents two running container: the actual one and Ryuk started by Testcontainers core to clean up after integration testing is done." class="wp-image-12009191" srcset="https://blog.codersee.com/wp-content/uploads/2024/09/image.png 756w, https://blog.codersee.com/wp-content/uploads/2024/09/image-300x75.png 300w" sizes="(max-width: 756px) 100vw, 756px" /></figure>



<p>Long story short, this container is responsible for removing containers/networks/volumes created by our test cases. So, even if we do not clean the environment ourselves- for example with the <code>stop()</code> function- the Ryuk container will take care of that. </p>



<h3 class="wp-block-heading" id="h-test-properties-with-dynamicpropertysource">Test Properties With DynamicPropertySource</h3>



<p>With that done, we need to update our environment configuration. </p>



<p>If we try to run our Spring Boot application at this point, our logic responsible for communication with Amazon S3 will try to reach the <strong>actual AWS instance</strong>. It will use the defaults, or make use of the things we configured in the <code>application.yaml</code>. </p>



<p>And this is not what we want, right? Instead, we would like to connect to the Testcontainer LocalStack instance.  </p>



<p>In some examples, you might have seen the usage of application properties files. Nevertheless, if we want to be more flexible and make use of containers started on random ports, then the <strong>@DynamicPropertySource</strong> is our best friend here: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">companion object {
  val localStack: LocalStackContainer = LocalStackContainer(
    DockerImageName.parse("localstack/localstack:3.7.2")
  ).apply {
    start()
  }

  @JvmStatic
  @DynamicPropertySource
  fun overrideProperties(registry: DynamicPropertyRegistry) {
    registry.add("spring.cloud.aws.region.static") { localStack.region }
    registry.add("spring.cloud.aws.credentials.access-key") { localStack.accessKey }
    registry.add("spring.cloud.aws.credentials.secret-key") { localStack.secretKey }
    registry.add("spring.cloud.aws.s3.endpoint") { localStack.getEndpointOverride(S3).toString() }
  }

}</pre>



<p>Thanks to that annotation, we can dynamically provide values to our test environment <strong>based on the LocalStack instance</strong>.</p>



<p>Of course, we must remember that methods annotated with <em>@DynamicPropertySource</em> <strong>must be static</strong>! And that&#8217;s why we use it with the @JvmStatic annotation.</p>



<h2 class="wp-block-heading" id="h-utilize-localstack-aws-cli">Utilize LocalStack AWS CLI</h2>



<p>At this point, we have our base class ready, but before we head to the tests, I would like to show you the <strong>LocalStack AWS CLI</strong> and why and how to use it.  </p>



<p>As the first step, let&#8217;s create the <code>util</code> package and add the <code>LocalStackUtil.kt</code> file:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import org.testcontainers.containers.localstack.LocalStackContainer

fun LocalStackContainer.createBucket(bucketName: String) {
  this.execInContainer("awslocal", "s3api", "create-bucket", "--bucket", bucketName)
}

fun LocalStackContainer.deleteBucket(bucketName: String) {
  this.execInContainer("awslocal", "s3api", "delete-bucket", "--bucket", bucketName)
}

fun LocalStackContainer.deleteObject(bucketName: String, objectName: String) {
  this.execInContainer("awslocal", "s3api", "delete-object", "--bucket", bucketName, "--key", objectName)
}</pre>



<p>As we can see, we introduced 3 helper extension functions that we will later use to create and delete buckets and objects. This way, we can <strong>easily clean up</strong> between the tests (we use the shared approach, right?). Moreover, it will <strong>simplify the setup process</strong> for each test case.</p>



<p>The above code combines the <code>execInContainer</code> &#8211; which will run the passed command in our running LocalStack container, just like with the <code>docker exec</code>, and the <code>awslocal</code>&#8211; a LocalStack wrapper around the AWS CLI. So, if you&#8217;ve ever been working with the AWS command line interface, then you will see that this is 1:1. </p>



<p>Unfortunately, we must provide the command as a separate String value, because otherwise, we will end up with: </p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: exec: &#8220;awslocal s3api create-bucket &#8211;bucket bucket-1&#8221;: executable file not found in $PATH: unknown</p>
</blockquote>



<h2 class="wp-block-heading" id="h-write-integration-test-cases">Write Integration Test Cases</h2>



<p>With all of that LocalStack preparation done (I know, quite a bunch of things to learn, but once you learn this, it will be a simple copy-paste), we can finally write some integration tests for our Spring Boot S3 integration.</p>



<p>Firstly, let&#8217;s create the <code>controller</code> package and put the <code>BucketControllerIntegrationTest</code> class:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class BucketControllerIntegrationTest(
  @Autowired private val webTestClient: WebTestClient
) : LocalStackIntegrationTest() { }</pre>



<p>As we can see, no annotations are required. We simply extend the <code>LocalStackIntegrationTest</code> class and inject the <code>WebTestClient</code>.</p>



<h3 class="wp-block-heading" id="h-test-no-buckets-exist">Test No Buckets Exist</h3>



<p>Nextly, let&#8217;s introduce our first test case. If we do not do anything, we expect that no buckets exist in our S3 instance: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Test
fun `Given no existing buckets When getting list of buckets Then return an empty array`() {
  val buckets = webTestClient
    .get().uri("/buckets")
    .exchange()
    .expectStatus().isOk()
    .expectBody(object : ParameterizedTypeReference&lt;List&lt;String>>() {})
    .returnResult()
    .responseBody

  assertNotNull(buckets)
  assertTrue(buckets.isEmpty())
}</pre>



<p>As mentioned before, we use the <em>WebTestClient</em> to make a GET HTTP request to the <code>/buckets</code> endpoint. Then, we use a small hack with <code>ParameterizedTypeReference</code>&#8211; because the endpoint returns a list of Strings and we use Kotlin- and we obtain the response body. </p>



<p>Lastly, we have plain assertions. We verify that the response body is not null and that our S3 bucket list is empty.</p>



<h3 class="wp-block-heading" id="h-verify-s3-bucket-exists-in-localstack">Verify S3 Bucket Exists In LocalStack</h3>



<p>Following, let&#8217;s see our helper functions in action:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Test
fun `Given one existing bucket When getting list of buckets Then return an array with expected bucket name`() {
  val bucketName = "bucket-1"
  localStack.createBucket(bucketName)

  val expectedJson = """
    [ "Bucket #1: $bucketName" ]
  """

  webTestClient
    .get().uri("/buckets")
    .exchange()
    .expectStatus().isOk()
    .expectBody()
    .json(expectedJson)

  localStack.deleteBucket(bucketName)
}</pre>



<p>This time, we utilize the <code>createBucket</code> and make sure that the <code>/buckets</code> endpoint returns the expected JSON. Please note that this is another way to assert the response body.   </p>



<p>After all, we delete the existing bucket, so it won&#8217;t affect other test cases.</p>



<h3 class="wp-block-heading" id="h-assert-bucket-created-successfully">Assert Bucket Created Successfully</h3>



<p>As the next step, let&#8217;s take a look at how we can check if our endpoint responsible for creating new S3 buckets works. And I see two paths we can go here.</p>



<p>The first one, using the <code>execInContainer</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Test
fun `Given no existing buckets When creating bucket Then create bucket successfully`() {
  val bucketName = "bucket-2"
  
  webTestClient
    .post().uri("/buckets")
    .bodyValue(BucketRequest(bucketName = bucketName))
    .exchange()
    .expectStatus().isOk()
  
  val execResult = localStack.execInContainer("awslocal", "s3api", "list-buckets").stdout
  
  assertTrue(execResult.contains(bucketName))  
  localStack.deleteBucket(bucketName)
}</pre>



<p>The important thing to mention here is that the <code>execInContainer</code> returns the <code>ExecResult</code>. And thanks to that, we can read additional info, like <code>stdout</code>, <code>stderr</code>, or <code>exitCode</code>.</p>



<p>And thanks to the <code>stdout</code>, we can get this JSON to verify it contains particular bucket name (or even we could parse that to an object): </p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
  "Buckets": [
    {
      "Name": "bucket-2",
      "CreationDate": "2024-09-19T05:28:42.000Z"
    }
  ],
  "Owner": {
    "DisplayName": "webfile",
    "ID": "75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a"
  }
}</pre>



<p>Alternatively, we can use the <code>/buckets</code> endpoint once again, too:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Test
fun `Given no existing buckets When creating bucket Then create bucket successfully`() {
  val bucketName = "bucket-2"

  webTestClient
    .post().uri("/buckets")
    .bodyValue(BucketRequest(bucketName = bucketName))
    .exchange()
    .expectStatus().isOk()

  val expectedJson = """
    [ "Bucket #1: $bucketName" ]
  """
  webTestClient
    .get().uri("/buckets")
    .exchange()
    .expectStatus().isOk()
    .expectBody()
    .json(expectedJson)

  localStack.deleteBucket(bucketName)
}</pre>



<h3 class="wp-block-heading" id="h-test-remaining-cases">Test Remaining Cases</h3>



<p>The remaining cases of our integration test use a more or less similar approach, so I will simply copy-paste them here so that you can analyze them. </p>



<p>At this point, I am pretty sure you understand the general idea behind what I understand by testing of Spring Boot S3 integration with LocalStack, so I don&#8217;t see the need for explaining them one- by one:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Test
fun `Given no objects existing in the bucket When getting objects of a bucket Then return an empty array`() {
  val bucketName = "bucket-3"
  localStack.createBucket(bucketName)

  val objects = webTestClient
    .get().uri("/buckets/$bucketName/objects")
    .exchange()
    .expectStatus().isOk()
    .expectBody(object : ParameterizedTypeReference&lt;List&lt;String>>() {})
    .returnResult()
    .responseBody

  assertNotNull(objects)
  assertTrue(objects.isEmpty())

  localStack.deleteBucket(bucketName)
}

@Test
fun `Given no objects When creating example object Then return created object`() {
  val bucketName = "bucket-4"
  val objectName = "example.json"
  localStack.createBucket(bucketName)

  val expectedJson = """
    {
      "id": "123",
      "name": "Some name"
    }
  """

  webTestClient
    .post().uri("/buckets/$bucketName/objects")
    .exchange()
    .expectStatus().isOk()
    .expectBody()
    .json(expectedJson)

  localStack.deleteObject(bucketName, objectName)
  localStack.deleteBucket(bucketName)
}

@Test
fun `Given created object When getting list of objects Then return array with one object`() {
  val bucketName = "bucket-5"
  val objectName = "example.json"
  localStack.createBucket(bucketName)

  val expectedJson = """
    [ $objectName ]
  """

  webTestClient
    .post().uri("/buckets/$bucketName/objects")
    .exchange()
    .expectStatus().isOk()

  webTestClient
    .get().uri("/buckets/$bucketName/objects")
    .exchange()
    .expectStatus().isOk()
    .expectBody()
    .json(expectedJson)

  localStack.deleteObject(bucketName, objectName)
  localStack.deleteBucket(bucketName)
}

@Test
fun `Given existing object When getting object by key Then return object content`() {
  val bucketName = "bucket-6"
  val objectName = "example.json"
  localStack.createBucket(bucketName)

  val expected = """
    {
      "id": "123",
      "name": "Some name"
    }
  """

  webTestClient
    .post().uri("/buckets/$bucketName/objects")
    .exchange()

  webTestClient
    .get().uri("/buckets/$bucketName/objects/$objectName")
    .exchange()
    .expectStatus().isOk()
    .expectBody()
    .json(expected)

  localStack.deleteObject(bucketName, objectName)
  localStack.deleteBucket(bucketName)
}

@Test
fun `Given existing bucket with object When deleting bucket Then bucket is removed`() {
  val bucketName = "bucket-7"
  localStack.createBucket(bucketName)

  webTestClient
    .post().uri("/buckets/$bucketName/objects")
    .exchange()
    .expectStatus().isOk()

  webTestClient
    .delete().uri("/buckets/$bucketName")
    .exchange()
    .expectStatus().isOk()

  val buckets = webTestClient
    .get().uri("/buckets")
    .exchange()
    .expectStatus().isOk()
    .expectBody(object : ParameterizedTypeReference&lt;List&lt;String>>() {})
    .returnResult()
    .responseBody

  assertNotNull(buckets)
  assertTrue(buckets.isEmpty())
}</pre>



<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<p>And that is all for this tutorial, in which we learned how to implement <strong>integration tests </strong>for <strong>Spring Boot AWS S3 </strong>integration with <strong>LocalStack </strong>and <strong>Testcontainers.</strong></p>



<p>I hope you enjoyed it and for the source code, please visit <a href="https://github.com/codersee-blog/spring-boot-3-kotlin-aws-s3-localstack-testcontainers" target="_blank" rel="noreferrer noopener">this GitHub repository</a>. </p>



<p>Have a great day and see you in the next articles! 🙂 </p>
<p>The post <a href="https://blog.codersee.com/test-spring-boot-aws-s3-with-localstack-and-testcontainers/">Test Spring Boot AWS S3 with Localstack and Testcontainers</a> appeared first on <a href="https://blog.codersee.com">Codersee blog- Kotlin on the backend</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.codersee.com/test-spring-boot-aws-s3-with-localstack-and-testcontainers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: blog.codersee.com @ 2026-05-20 04:11:12 by W3 Total Cache
-->