{"record":{"id":"de80a746ef42d457","repo":"testcontainers/testcontainers-java","slug":"mongodbcontainer-should-be-started-first","errorCode":null,"errorMessage":"MongoDBContainer should be started first","messagePattern":"MongoDBContainer should be started first","errorType":"exception","errorClass":"IllegalStateException","httpStatus":null,"severity":"error","filePath":"modules/mongodb/src/main/java/org/testcontainers/containers/MongoDBContainer.java","lineNumber":126,"sourceCode":"\n    /**\n     * Gets a replica set url for the default {@value #MONGODB_DATABASE_NAME_DEFAULT} database.\n     *\n     * @return a replica set url.\n     */\n    public String getReplicaSetUrl() {\n        return getReplicaSetUrl(MONGODB_DATABASE_NAME_DEFAULT);\n    }\n\n    /**\n     * Gets a replica set url for a provided <code>databaseName</code>.\n     *\n     * @param databaseName a database name.\n     * @return a replica set url.\n     */\n    public String getReplicaSetUrl(final String databaseName) {\n        if (!isRunning()) {\n            throw new IllegalStateException(\"MongoDBContainer should be started first\");\n        }\n        return getConnectionString() + \"/\" + databaseName;\n    }\n\n    private String[] buildMongoEvalCommand(final String command) {\n        return new String[] {\n            \"sh\",\n            \"-c\",\n            \"mongosh mongo --eval \\\"\" + command + \"\\\"  || mongo --eval \\\"\" + command + \"\\\"\",\n        };\n    }\n\n    private void checkMongoNodeExitCode(final Container.ExecResult execResult) {\n        if (execResult.getExitCode() != CONTAINER_EXIT_CODE_OK) {\n            final String errorMessage = String.format(\"An error occurred: %s\", execResult.getStdout());\n            log.error(errorMessage);\n            throw new ReplicaSetInitializationException(errorMessage);\n        }","sourceCodeStart":108,"sourceCodeEnd":144,"githubUrl":"https://github.com/testcontainers/testcontainers-java/blob/8e549514e3f01c57d70546fbb8599d138f3903e5/modules/mongodb/src/main/java/org/testcontainers/containers/MongoDBContainer.java#L108-L144","documentation":"MongoDBContainer.getReplicaSetUrl(databaseName) builds a replica-set connection string from the running container's connection string. If the container is not currently running, it throws this IllegalStateException because there is no valid endpoint to build a URL from.","triggerScenarios":"Calling getReplicaSetUrl(...) before start() has completed, after stop(), or from an accessor that runs before the container lifecycle hook (e.g. a static field initializer, @BeforeAll order issue, or a failed start that left the container stopped).","commonSituations":"Constructing a MongoClient in a field initializer before JUnit starts the container; reusing a container reference after a test class stopped it; a start() failure silently swallowed upstream.","solutions":["Start the container (container.start() or @Container with Testcontainers extension) before calling getReplicaSetUrl","Ensure the container reference used in the test is the same started instance (static + @Container pattern)","If building clients eagerly, defer client construction until after start"],"exampleFix":"// before\nstatic MongoDBContainer mongo = new MongoDBContainer(\"mongo:6\");\nMongoClient client = MongoClients.create(mongo.getReplicaSetUrl(\"mydb\")); // throws: not started\n// after\n@Container\nstatic MongoDBContainer mongo = new MongoDBContainer(\"mongo:6\");\n@BeforeAll\nstatic void init() {\n    MongoClient client = MongoClients.create(mongo.getReplicaSetUrl(\"mydb\"));\n}","handlingStrategy":"validation","validationCode":"if (!mongo.isRunning()) {\n    mongo.start(); // or fail fast with a clear message\n}\nString url = mongo.getReplicaSetUrl(\"mydb\");","typeGuard":null,"tryCatchPattern":"try {\n    String url = mongo.getReplicaSetUrl(\"mydb\");\n} catch (IllegalStateException e) {\n    throw new IllegalStateException(\"MongoDBContainer not started; check @Container wiring\", e);\n}","preventionTips":["Use @Testcontainers with @Container static fields to enforce lifecycle","Never read container URLs in field initializers","Assert container.isRunning() in @BeforeAll before dependent setup"],"tags":["mongodb","testcontainers","lifecycle","illegal-state"],"backgroundTag":"invalid-state-transition","analyzedSha":"8e549514e3f01c57d70546fbb8599d138f3903e5","analyzedAt":"2026-09-12T14:56:41.227Z","contentChangedAt":"2026-09-12T14:56:41.227Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}