junitテストをする時にSpring+jpaトランザクションを利用する
Javaコード:
package com.startnews24.springstu.applicationImpl;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.transaction.annotation.Transactional;
import com.startnews24.springstu.application.UserApplication;
import com.startnews24.springstu.core.User;
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = “classpath*:META-INF/spring/ApplicationContext.xml")
@TransactionConfiguration(transactionManager = “transactionManager", defaultRollback = true)
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
TransactionalTestExecutionListener.class })
public class UserApplicationImplTest extends AbstractJUnit4SpringContextTests {
private Logger logger = Logger.getLogger(this.getClass());
@Resource(name = “userApplication")
private UserApplication userApplication;
@Test
public void Startnews24Spring() {
logger.info(“検証開始");
List<User> users = userApplication.find(“from User");
for (User user : users) {
userApplication.delete(user);
}
}
}