Why doesn't Junit test throw javax.persistence.PersistenceException?

久未见 提交于 2019-12-11 03:43:55

问题


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.

来源:https://stackoverflow.com/questions/32759864/why-doesnt-junit-test-throw-javax-persistence-persistenceexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!