Skip to content

Bug Report: NullPointerException when creating Db2Container #542

@k-higuchi0440

Description

@k-higuchi0440

Hi, I would like to report a bug below!

Description

The Db2Container class throws a NullPointerException during instantiation due to calling inherited username and password methods before the underlying container is initialized.

Reproduction Code

  import com.dimafeng.testcontainers.Db2Container
  import org.testcontainers.utility.DockerImageName

  // This will throw NullPointerException
  val container = Db2Container(
    dockerImageName = DockerImageName.parse("icr.io/db2_community/db2:11.5.9.0")
  )

Error Message

  java.lang.NullPointerException: Cannot invoke "org.testcontainers.containers.JdbcDatabaseContainer.getUsername()" because the return value of "com.dimafeng.testcontainers.SingleContainer.underlyingUnsafeContainer()" is null
    at com.dimafeng.testcontainers.JdbcDatabaseContainer.username(JdbcDatabaseContainer.scala:17)
    at com.dimafeng.testcontainers.Db2Container.(Db2Container.scala:19)

Root Cause

In the Db2Container.scala source code, lines 19-20 call username and password:

case class Db2Container(
  dockerImageName: DockerImageName = ...,
  dbName: String = ...,
  dbUsername: String = Db2Container.defaultUsername,    // constructor parameter
  dbPassword: String = Db2Container.defaultPassword,    // constructor parameter
  ...
) extends SingleContainer[JavaDb2Container] with JdbcDatabaseContainer {

  override val container: JavaDb2Container = {
    val c = new JavaDb2Container(dockerImageName)
    c.withDatabaseName(dbName)
    c.withUsername(username)  // ← JdbcDatabaseContainer method is called
    c.withPassword(password)  // ← same as above
    c.acceptLicense()
    ...
  }
}

These username and password are methods from the JdbcDatabaseContainer trait that call underlyingUnsafeContainer.getUsername() and underlyingUnsafeContainer.getPassword(). However, since these are called during container field initialization, underlyingUnsafeContainer is still null, causing a NullPointerException.

Fix Proposal

Change lines 19-20 to use the constructor parameters directly:

  c.withUsername(dbUsername)
  c.withPassword(dbPassword) 

Environment

  • testcontainers-scala-db2: 0.43.6
  • Scala: 2.13
  • Error occurs in both TestContainersForAll and manual container creation

My environmennt is a little old but this bug exists in the current master branch and affects all versions using the current implementation. The issue prevents any usage of the Db2Container class.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions