Database and mocking / DI

I’m trying to implement a basic web app with any rust framework (tried actix and rocket). In spring I’d do the following: controller Calls service(s) (which starts a transaction) which calls multiple repositories. Each layer is represented as an interface. The charm is that when i unit test my service i can implement a mock repository and pass that in the constructor of my service under test, like making sure it returns a user record.

Now the rust story: default behavior of the web frameworks is to pass the db pool to the handler function. Then you pass that down all the way. This makes every method not unittestable. I cannot call the method without passing a db connection. I cannot mock away the dependency.

The alternative i tried is to create trait objects of the userrepository and registrationservice. Then i can initiate the userservice with a mock repo that implements that trait and pass it. Is there a better way?

The second problem is transactions. A transaction spans usually many repository calls. But In above architecture only the repository holds a db pool reference. What would be the best way to start a transaction in the service?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.