Mocking mongodb


I am currently developing an api with actix_web and I use mongodb (official crate) as my database. I now want to write unit tests for my controller, which is the part of my code that interacts with the database, make the queries, and Deserialize the returned BSON documents into custom structs. Basically, each route handler calls the related controller to interact with the db.

The issue is I cannot find any way to properly mock or stub the database.

I though of hiding my interface behind a custom trait and implement a mock structure that implements that trait but I think it raises 2 major issues:

  • First I'll need to implement a lot of traits and such to get to the bottom of the mongodb crate and be able to mock a for loop over a cursor for instance
  • Second, if I do that, I'll basically rewrite exactly what my controller is doing already, and I won't test this code then ... I can easily test routes handler by mocking my controller, but not test my controller by mocking it itself...

I though of integration testing with a mongodb docker, and I think it will be possible, but it does not replace good unit testing.

Has anyone here already stumble on this issue and has a good idea to solve it ?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.