编写junit单元测试

来源:互联网 发布:网络部招新面试问题 编辑:程序博客网 时间:2024/06/05 10:40

1.编写java代码块

引入包:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

// 引入beans.xml文件

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/conf/spring/*-beans.xml")
public class StockServiceImplTest {
    /** The i stock dao. */
    @Autowired
    private IStockDao iStockDao;
    @Test
    public void testSaveNotLoginStockToLogin() throws Exception {
        System.err.println(JSON.toJSONString("1111111"));
        queryStockReq req = new queryStockReq();
        req.setUser_id("af1fc57d58324ddaa332b6d1abf7c49c");
        req.setSystem_id("10");
        List<queryStockRes> queryResList = iStockDao.queryStock(req);
        System.err.println("queryResList:" + JSON.toJSONString(queryResList));
        System.err.println(JSON.toJSONString("2222222"));
    }
}

以上可以参考,我的代码片,StockServiceImplTest

可以编写一个BaseTest,加载

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/conf/spring/*-beans.xml")

其余的Test类都继承BaseTest类


2.beans.xml文件

将对应的beans.xml文件放在


dataSource的引入(&amp;相当于url中的&符号):

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl">
<value>jdbc:mysql://****:3306/itn_stockwin?useUnicode=true&amp;characterEncoding=UTF-8</value>
</property> 
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="user" value="stockwin" />
<property name="password" value="stockwin" />
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="100" />
<!--连接池中保留的最小连接数。 -->
<property name="minPoolSize" value="1" />
<!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="10" />
    <property name="maxIdleTime" value="25000"/> 
   <property name="acquireIncrement" value="1"/> 
   <property name="acquireRetryAttempts" value="30"/> 
   <property name="acquireRetryDelay" value="1000"/> 
   <!-- 获取connnection时测试是否有效 -->
   <property name="testConnectionOnCheckin" value="true"/> 
   <!-- 自动测试的table名称,可以自己建个空表来做测试  --> 
   <property name="automaticTestTable" value="test_table111"/> 
   <!-- 设置时间必须少于MySQl wait_timeou -->
   <property name="idleConnectionTestPeriod" value="18000"/>  
   <!-- 设置时间必须少于MySQl wait_timeout -->
   <property name="checkoutTimeout" value="5000"/> 
</bean>

如果是spring注解方式定义的service和controller等,注意引入扫描包:

<context:component-scan  base-package="com.mvc.controller"/>

<context:component-scan base-package="com.*.*.*"/>  其中com.*.*.*为包地址

还有mapper 扫描配置、事务配置等

建议,直接将\src\main\resources目录下的配置拷贝过来,并加以修改,使其正常加载即可

0 0