Announcement Announcement Module
Collapse
No announcement yet.
No Duplicate entry exception on transactional test Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • No Duplicate entry exception on transactional test

    Hi Everyone!

    I created a simple application for using EntityManager with spring transaction. I have a user table where usernames are unique. When I try to create a new user with existing username it throws an exception.

    I setted up transaction testing with following scenarios:
    -When I create a new non existing user I can query it during the test, and at the end of the test it will rolled back automatically.
    -When I create a new existing user I got an expected exception.
    -The problem: When I create a new non existing user it works fine. But when I create it second time I did not get exception. Why?

    The test case:
    Code:
    @Test
    @ExpectedException(DataAccessException.class)
    public void testCreateUsers(){
    	UserEntity entity = new UserEntity();
    	entity.setPassword("password");
    	entity.setUsername("username");
    	entity.setRole(RoleList.ROLE_SUPERVISOR);
    	userService.createUser(entity);
    		
    	UserEntity result = userService.loadUserByUsername("username");
    	assertEquals("username", result.getUsername());
    	
    	UserEntity entity2 = new UserEntity();
    	entity2.setPassword("password");
    	entity2.setUsername("username");
    	entity2.setRole(RoleList.ROLE_SUPERVISOR);
    	userService.createUser(entity2);
    }
    And the JUnit output:
    java.lang.AssertionError: Expected exception: org.springframework.dao.DataAccessException

  • #2
    Everything runs in a single transactions (I assume here you are using a transactional test case). So to actually issue a query to the database you need to call flush on your entity manager, flush is in general automatically called before you execute a query (flush mode auto) and that is the reason why you can query and find the user.

    Comment


    • #3
      Originally posted by Marten Deinum View Post
      Everything runs in a single transactions (I assume here you are using a transactional test case). So to actually issue a query to the database you need to call flush on your entity manager, flush is in general automatically called before you execute a query (flush mode auto) and that is the reason why you can query and find the user.
      Thank you very much! It works

      Comment

      Working...
      X