利用 spring test 实现自动启动spring 容器进行 JPA接口测试

自动启动context JPA接口测试



import com.alibaba.druid.pool.DruidDataSource;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;


@ContextConfiguration(locations = {
        "classpath:applicationContext-commons-configuration.xml",
        "classpath:applicationContext-commons-cache.xml",
        "classpath:applicationContext-commons-spring.xml",
        "classpath:applicationContext-oaml-core.xml"
})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
@TestPropertySource(properties = "application.name = xxx-aml")
public abstract class BaseTest extends AbstractTransactionalJUnit4SpringContextTests{
    
    static final Logger LOGGER = LoggerFactory.getLogger(BaseTest.class);
    
    @PersistenceContext
    protected EntityManager entityManager;
    @Autowired
    protected static ApplicationContext applicationContext;
    
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        LOGGER.info("loadJndiDataSource start");
        final SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
        
        final DruidDataSource profileDS = new DruidDataSource();
        profileDS.setDriverClassName("com.mysql.jdbc.Driver");
        profileDS.setUrl("jdbc:mysql://127.0.0.1:7954/dev_profile?characterEncoding=utf-8");
        profileDS.setUsername("xxx-dev");
        profileDS.setPassword("xxx");
        profileDS.setInitialSize(1);
        profileDS.setMaxActive(20);
        profileDS.setMaxWait(60000);
        profileDS.setMinEvictableIdleTimeMillis(300000);


        final DruidDataSource oamlDS = new DruidDataSource();
        oamlDS.setDriverClassName("com.mysql.jdbc.Driver");
        oamlDS.setUrl("jdbc:mysql://127.0.0.1:7954/dev_oaml?characterEncoding=utf-8");
        oamlDS.setUsername("xxx-dev");
        oamlDS.setPassword("xxxxx");
        oamlDS.setInitialSize(1);
        oamlDS.setMaxActive(20);
        oamlDS.setMaxWait(60000);
        oamlDS.setMinEvictableIdleTimeMillis(300000);

        builder.bind("java:comp/env/jdbc/PROFILEDS", profileDS);
        builder.bind("java:comp/env/jdbc/OAMLDS", oamlDS);
        builder.activate();
        LOGGER.info("loadJndiDataSource END");
    }

你可能感兴趣的:(Java,spring,java,后端)