JUnit 单元测试的数据源配置

 

1. 配置用于本地测试时的XML文件,模拟tomcat的数据库jndi

  
  

  
  
  
  
  
  
   

2. JunitBaseTest

import javax.sql.DataSource;

import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= { 
        "file:WebContent/WEB-INF/applicationContext-*.xml",
        "file:WebContent/WEB-INF/mvc-dispatcher-servlet.xml"
    })
public class JunitBaseTest {
    
    @BeforeClass
    public static void beforeClass() throws Exception {
        ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("file:WebContent/WEB-INF/jndiTest.xml");
        DataSource ds = (DataSource) app.getBean("dataSource");
        SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
        builder.bind("jndiName", ds);
        builder.activate();
        app.close();
    }
}

3. TingTest  单元测试

import java.io.IOException;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class TingTest extends JunitBaseTest {

    private static final Logger logger = Logger.getLogger(TingTest.class);

   
    @Autowired
    TingMapper tingMapper;

    @Test
    public void tingTest() throws IOException, InterruptedException {
        try {
            String res =
                    "{\"error_code\":0,\"reason\":\"ok\",\"result\":{\"path\":[{\"type\":\"name\",\"value\":\"李彦宏\"},{\"type\":\"percent\",\"value\":\"99.50%\"},{\"type\":\"name\",\"value\":\"北京百度网讯科技有限公司\"}],\"structure\":{\"id\":\"22822\",\"name\":\"北京百度网讯科技有限公司\",\"type\":\"C\",\"amount\":null,\"percent\":null,\"sh_type\":null,\"children\":[{\"id\":\"1984012283\",\"name\":\"李彦宏\",\"type\":\"H\",\"amount\":\"2142.36\",\"percent\":\"99.50%\",\"sh_type\":\"工商股东\",\"children\":[],\"regCapital\":null,\"parentName\":null,\"actualHolding\":true},{\"id\":\"1839080315\",\"name\":\"向海龙\",\"type\":\"H\",\"amount\":\"1085.64\",\"percent\":\"0.50%\",\"sh_type\":\"工商股东\",\"children\":[],\"regCapital\":null,\"parentName\":null,\"actualHolding\":false}],\"regCapital\":\"217128\",\"parentName\":null,\"actualHolding\":true}}}";
            JSONObject json = JSON.parseObject(res);
            int errorCode = json.getIntValue("error_code");
            if (errorCode == 0) {
                JSONObject result = json.getJSONObject("result");
                JSONArray path = result.getJSONArray("path");
                tingMapper.savePath(relationId, path);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

你可能感兴趣的:(JUnit 单元测试的数据源配置)