IllegalStateException during Spock test of transactional service

with No Comments

Have you ever experienced the following error in a unit test :

java.lang.IllegalStateException: No transactionManager was specified. Using @Transactional or @Rollback requires a valid configured transaction manager. If you are running in a unit test ensure the test has been properly configured and that you run the test suite not an individual test method.

If yes, then welcome. The post will describe how to solve the following error in unit test.

I will give a simple example of the situations when it occurs. There are two transactional services: UserService with the createUser method to create the user, and RoleService with the grantRole method to assign a specific role to the user at the time of its creation. Here is the code:

You need to test the createUser method. Here is an example of a test:

I mock service RoleService using Spy object for the purpose of calling the real method. When running the test, we get the error mentioned above. To solve it, you need to specify the transaction manager for the RoleService service:

Run the test again and it works as expected.

I hope this article will be of a great use for you.

Useful links:

https://github.com/AndrewShitsko/mock-transaction-manager

http://spockframework.org/spock/docs/1.1-rc-4/all_in_one.html

Leave a Reply