How do i write Junit4 tests without Spring transactional test support?
I would like to test transaction rollbacks in my application service. As a 开发者_开发技巧result i do not want to use spring's AbstractTransactionalJUnit4SpringContextTests
with the @Transactional
annotation as that wraps my test method in a transaction.
I know spring also offers AbstractJUnit4SpringContextTests
for tests without transactions. However i need to have some transactions to save data into my database and also query data for assertions after running the service under test.
How can i write a Junit 4 spring transactional test without the default transaction test management?
Here is the answer to your question ;
@ContextConfiguration(value = "/applicationContext.xml")
public class JPASpringTest extends AbstractJUnit4SpringContextTests {
@PersistenceContext(unitName="jpadenemelocal")
EntityManager entityManager;
@Autowired
protected PlatformTransactionManager transactionManager;
@Test
public void testInsertRolManyToMany() {
TransactionStatus status = transactionManager.getTransaction(null);
// your code
transactionManager.commit(status);
}
}
The spring docs should cover this in their testing chapter
What you might want is to configure your test without the default TransactionalTestExecutionListener like this
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,DirtiesContextTestExecutionListener.class})
public class SimpleTest {
@Test
public void testMethod() {
// execute test logic...
}
}
精彩评论