2

I have 2 JUnit tests in the same test class each one marked as @Transactional, the first one create users and the second one create users and check that we can get these users.

The problem is that when the second test runs, users created by the first test is still in the DB.

@Test
@Transactional
public void testCreateUser() throws Exception

@Test
@Transactional
public void testGetUserById() throws Exception

Do you have any idea why @Transactional is not working well in the same test class? Furthermore data is rolled back at the end of the test class.

I'm using Spring boot + Mysql + Hibernate.

Thank you for your time.

error
  • 926
  • 3
  • 10
  • 19
  • are you executing unit tests or integration tests ? – Vasu Oct 30 '16 at 20:35
  • you defined a transactionManager() ? : http://stackoverflow.com/a/35943700/641627 – alexbt Oct 30 '16 at 20:48
  • 1
    I tried to do it but i had some errors like `Could not open ServletContext resource [/application.properties]` @Transactional is made for that purpose, why isn't it working ? – error Oct 30 '16 at 23:45

2 Answers2

0

Try something like this and take care about classpath of your ...context.xml. You can also move @Transactional above class if you want every method to be transactional or above each method you want.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:/config/your-context.xml","classpath:/config/ehcache.xml"})
@Transactional
@WebAppConfiguration
public class IntegrationTests {

@Autowired
private ApplicationContext appContext;

@Autowired
public FileDao fileDao;

@Autowired
public SessionFactory sessionFactory;

@Test
public void test1() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException{
    ....
    ....
    ....
    }
}
paun90
  • 16
  • 2
  • Maybe it's working for Spring MVC, i tried to use application.properties as ContextConfiguration but it's not working – error Oct 31 '16 at 23:25
  • You use Spring boot, I didn't see, sorry. This works in Spring MVC. – paun90 Nov 01 '16 at 08:30
0

Add to configuration class @EnableTransactionManagement

Sergey Bulavkin
  • 2,325
  • 2
  • 17
  • 26