Why doesn't Junit test throw javax.persistence

2019-07-11 02:17发布

问题:

I run my JUnit4 test to test my JPA repository. But when I try to run this test, which have to throw javax.persistence.PersistenceException my test fails - it doesn't get needed exception. I've tried it on H2, HSQL, Derby and MySQL. Here it is:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:testContext.xml" })
@Transactional
@FixMethodOrder(MethodSorters.JVM)
public class RepositoryTestTemplate extends
        AbstractTransactionalJUnit4SpringContextTests {

}   

public class AccountRepositoryTest extends RepositoryTestTemplate {

    @Autowired
    AccountRepository accountRepository;

    @Test(expected = PersistenceException.class)
        public void doubleSaveMethodCallTest() {
            Account account = new Account();
            accountRepository.save(account);
            Account account2 = accountRepository.find(account.getId());
            accountRepository.save(account2);
        }
}

Here's my repository.

@Repository
public class JpaAccountRepository implements AccountRepository {

    @PersistenceContext
    EntityManager em;

    @Override
    @Transactional
    public void save(Account account) {
        em.persist(account);
    }
}

Entity:

 @Entity
    public class Account {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        protected Long id;

        public void setId(Long id) {
            this.id = id;
        }

        public Long getId() {
            return id;
        }

I get that exception when running in main class.