Search code examples
javasqlspring-data-jpajunit5

How to test a repository with a user that have update rights and the test needs tot add records to the database


I use mysql and spring 5, spring-data-jpa and spring-boot and JUnit5.

This must be a common problem but I don't see te sollution. I have to test a repository with a user that has only Update rights in the databse, but to perform the test I hava a sql script to inbject re number of record to perform my test on. How do i add record to the database (mysql) with a user that has create rights an perform my repository tests with a user that has only update rights.

Kind Greetings, Frank


Solution

  • you can define two different datasources for the same database: one using the update-rights user, and the other using the create-rights user.

    In order to do so, you can take a look at: Spring Boot Configure and Use Two DataSources

    and also to: https://www.baeldung.com/spring-data-jpa-multiple-databases

    Once you have defined both datasources, with their corresponding transaction managers, then you can specify which transaction manager / datasource applies within the @Transaction annotation configuration (previous reference shows an example with JUnit tests).

    By other hand, if you don't mind having a custom simplified database environment for executing junit tests, it would be easier to configure a spring profile with an in-memory database like H2, in which you could use the same user for everything. Anyway, this is a simplication of the database environment, and would miss testing your code on database fine-grained permissions (as I assume that is one of your goals).