第四步:写单元测试类
- package com.jackyan.practice.store.junit;
- import com.jackyan.practice.store.service.ProductBeanService;
- import com.jackyan.practice.store.service.mysql.ProductBeanServiceMysqlImpl;
- import junit.framework.TestCase;
- public class ProductServiceTest extends TestCase {
- public ProductBeanService pbs;
- public ProductServiceTest(String name){
- super(name);
- }
- protected void setUp()throws Exception{
- super.setUp();
- pbs=new ProductBeanServiceMysqlImpl();
- }
- protected void tearDown()throws Exception{
- super.tearDown();
- }
- public void testGetAllProductSimpleInformation()throws Exception{
- assertNotNull(pbs.getAllProductSimpleInformation());
- }
- public void testGetProductById()throws Exception{
- assertNotNull(pbs.getProductById(1));
- }
- }
第五步 编写工具类(其实这一步应该拿到第三步里)
- package com.jackyan.practice.store.util;
- import java.io.BufferedInputStream;
- import java.io.DataInputStream;
- import java.io.FileInputStream;
- import java.sql.Connection;
- import java.sql.SQLException;
- import java.util.Properties;
- import javax.sql.DataSource;
- import org.apache.commons.dbcp.BasicDataSourceFactory;
- public class ConnectionFactory {
- private static ConnectionFactory factory= new ConnectionFactory();
- private static DataSource source =null;
- private static String path="E://source//store//src//com//jackyan//practice//store//util//dbconfig.properties";
- static{
- try{
- /*还是老问题
- prop.load(ConnectionFactory.class.getClassLoader().getResourceAsStream("dbconfig.properties"));
- jvm无法自动搜索到配置文件。
- */
- Properties prop=new Properties();
- prop.load(new DataInputStream(new BufferedInputStream(new FileInputStream(path))));
- source=BasicDataSourceFactory.createDataSource(prop);
- }catch(Exception e){
- System.out.println("数据库连接池初始化失败");
- e.printStackTrace();
- }
- }
- private ConnectionFactory(){
- }
- public static ConnectionFactory getFactory(){
- return factory;
- }
- public static Connection getConnection(){
- try {
- return source.getConnection();
- } catch (SQLException e) {
- System.out.println("从数据库连接池获取链接时出现异常");
- return null;
- }
- }
- public static DataSource getDataDource(){
- return source;
- }
- }
- package com.jackyan.practice.store.util;
- import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
- public class Utils {
- private static SimpleJdbcTemplate jdbcTemplate=new SimpleJdbcTemplate(ConnectionFactory.getDataDource());
- private Utils(){
- }
- public static SimpleJdbcTemplate getJdbcTemplate() {
- return jdbcTemplate;
- }
- }
数据库连接池(dbcp)的配置文件dbconfig.properties
- #暂时使用dbcp连接池
- driverClassName=com.mysql.jdbc.Driver
- url=jdbc:mysql://localhost:3306/test
- username=root
- password=yanshujun
- #初始连接数
- initialSize=2
- #最大连接数
- maxActive=5
- #最大空闲连接数
- maxIdle=2
- #最小空闲连接数
- minIdle=0
- #超时等待最大时间(毫秒)
- maxWait=10000