0

I'm struggling to remove all data persisted in a Container using TestContainers. I'm able to create and retrieve data from MongoDB Test Container, but each test case should be self contained, and one test shouldn't affect another one. If I'm not able to 'clear' somehow my database, after testing 'Class A' there will be some 'dirty' in my database when executing tests for 'Class B'.

In a Spring Boot environment I can easily handle these situation using either:

@DirtyContext

or

    @Autowired
    MongoTemplate mongoTemplate
    
    @BeforeEach
    public void setup(){
        mongoTemplate.dropCollection(ClassName.class)
    }

I know that somehow I can execute some commands on the container, here's what I've done so far:

    private static final MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:latest");

    @SneakyThrows
    @Override
    public Map<String, String> start() {
        mongoDBContainer.start();
        return Collections.singletonMap("quarkus.mongodb.connection-string",
        mongoDBContainer.getReplicaSetUrl());

    }

    @Override
    public void stop() {
        mongoDBContainer.close();
    }

Trying to simply execute a show dbs hasn't got me anything.

@SneakyThrows
public void show(){
   mongoDBContainer.execInContainer("show dbs");
}

Am I able to connect to the container and manually execute a db.collection.drop()? If yes, I'd be gladly accept some tips and snippets. (Obs: Any API that do this would be even better).

Johnnes Souza
  • 361
  • 1
  • 8
  • 22

1 Answers1

0

Running mongoDBContainer.execInContainer("show dbs"); will execute the show dbs command on the container shell (sh or bash) not the MongoDB shell (mongos), that's why it didn't work.

The best you can do is inject a MongoClient inside your test and drop the collection in an @BeforeClass annotated method.

loicmathieu
  • 5,181
  • 26
  • 31
  • Well... that's exaplains a lot of the errors I was getting, I shoul have noticed it earlier. I'll try to Inject the MongoClient and execute the test like you said. – Johnnes Souza Feb 16 '21 at 12:43