Spring 单元测试

1、pom文件引入依赖

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		
		<dependency>
			<groupId>org.test4j</groupId>
			<artifactId>test4j.core</artifactId>
			<version>2.0.7</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.2.5.RELEASE</version>
		</dependency>

2.1、Spring单元测试基础类AbstractTransactionalTests.java

package com.fast.base;

import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.test4j.module.ICore;

@DirtiesContext
@ContextConfiguration(locations = { 
		"classpath*:/spring/applicationContext-test-core.xml",
		"classpath*:/spring/applicationContext-test-jdbc.xml"})
//@ContextConfiguration({ "classpath:spring/applicationContext-test-*.xml" })
@ActiveProfiles(profiles = "test")
@Rollback(true)//默认为true
public abstract class AbstractTransactionalTests extends AbstractTransactionalJUnit4SpringContextTests
		implements ICore {
}

2.2、单元测试类 DemoServiceTest.java

package com.fast.service;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.fast.base.AbstractTransactionalTests;

public class DemoServiceTest extends AbstractTransactionalTests{
	
	@Autowired
	DemoService demoService;

	@Test
	public void testCreate() {
		String id= "111";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("empId", id);
		map.put("leadId", "1");
		map.put("empName", "test");
		map.put("salary", "100");
		map.put("deptNo", "1");
		demoService.create(map);
		
		Map<String, Object> result = demoService.get(id);
		assertTrue(result != null && result.size() > 0);
	}

	@Test
	public void testDelete() {
		String id = "3";
		assertNotNull(demoService.get(id));
		demoService.delete(id);
		assertNull(demoService.get(id));
	}

}

3.1、applicationContext-test-jdbc.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:cache="http://www.springframework.org/schema/cache"  
    xsi:schemaLocation="  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context.xsd  
    http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans.xsd  
    http://www.springframework.org/schema/tx  
    http://www.springframework.org/schema/tx/spring-tx.xsd  
    http://www.springframework.org/schema/jdbc  
    http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd  
    http://www.springframework.org/schema/cache  
    http://www.springframework.org/schema/cache/spring-cache-3.1.xsd  
    http://www.springframework.org/schema/aop  
    http://www.springframework.org/schema/aop/spring-aop.xsd  
    http://www.springframework.org/schema/util  
    http://www.springframework.org/schema/util/spring-util.xsd">  
    
    <!-- 读取属性文件 -->
    <bean id="config"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc_test.properties"></property>
    </bean>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close">
        <property name="driverClassName" value="${driverClassName}" />
        <!-- 基本属性 url、user、password -->
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />

        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="10" />
        <property name="minIdle" value="10" />
        <property name="maxActive" value="200" />

        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000" />

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="5000" />

        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />

        <property name="validationQuery" value="SELECT 'x' FROM DUAL" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        
        <!-- 超过时间限制是否回收 -->  
		<property name="removeAbandoned" value="true" />  
		<!-- 超时时间;单位为秒。180秒=3分钟 -->  
		<property name="removeAbandonedTimeout" value="180" />  
		<!-- 关闭abanded连接时输出错误日志 -->  
		<property name="logAbandoned" value="true" />   

        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize"
            value="20" />

        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="stat" />
    </bean>
  
</beans> 

3.2、applicationContext-test-core.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:cache="http://www.springframework.org/schema/cache"  
    xsi:schemaLocation="  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context.xsd  
    http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans.xsd  
    http://www.springframework.org/schema/tx  
    http://www.springframework.org/schema/tx/spring-tx.xsd  
    http://www.springframework.org/schema/jdbc  
    http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd  
    http://www.springframework.org/schema/cache  
    http://www.springframework.org/schema/cache/spring-cache-3.1.xsd  
    http://www.springframework.org/schema/aop  
    http://www.springframework.org/schema/aop/spring-aop.xsd  
    http://www.springframework.org/schema/util  
    http://www.springframework.org/schema/util/spring-util.xsd"> 
    
    <!-- 扫描manager 引入注解 -->
    <context:component-scan base-package="com.fast" />
    <!-- 启用对事务注解的支持 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
    
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="create*" rollback-for="Exception" propagation="REQUIRED"/>
			<tx:method name="add*" rollback-for="Exception" propagation="REQUIRED"/>
			<tx:method name="save*" rollback-for="Exception" propagation="REQUIRED"/>
			<tx:method name="insert*" rollback-for="Exception" propagation="REQUIRED"/>
			<tx:method name="delete*" rollback-for="Exception" propagation="REQUIRED"/>
			<tx:method name="update*" rollback-for="Exception" propagation="REQUIRED"/>
			<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
			<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
			<tx:method name="query*" propagation="SUPPORTS" read-only="true"/>
			<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
		</tx:attributes>
	</tx:advice>
	
	<aop:config>
		<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.fast..*Service*.*(..))"/>
		<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.fast..*manager*.*(..))"/>
	</aop:config>

</beans> 

3.3、jdbc_test.properties

driverClassName=oracle.jdbc.driver.OracleDriver
jdbc_url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc_username=TEST
jdbc_password=TEST

4、项目结构
项目结构

参考:
java spring 单元测试_使用 Spring 进行单元测试
https://blog.csdn.net/weixin_34649105/article/details/114207434

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring中进行单元测试时,可以使用JUnit和Mockito等测试框架来编写和执行测试代码。以下是配置Spring单元测试的一般步骤: 1. 在测试类上添加注解 `@RunWith(SpringRunner.class)`,它会告诉JUnit使用Spring提供的测试运行器来运行测试。 例如: ```java @RunWith(SpringRunner.class) public class MyTest { // 测试代码 } ``` 2. 在测试类上使用注解 `@ContextConfiguration` 来指定Spring应用程序上下文的配置。你可以指定一个XML配置文件的路径,或是直接指定一个配置类。 例如,使用XML配置文件: ```java @RunWith(SpringRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml") public class MyTest { // 测试代码 } ``` 或者,使用配置类: ```java @RunWith(SpringRunner.class) @ContextConfiguration(classes = MyConfig.class) public class MyTest { // 测试代码 } ``` 3. 使用注解 `@Autowired` 或 `@Resource` 自动注入需要进行测试的bean。 例如: ```java @RunWith(SpringRunner.class) @ContextConfiguration(classes = MyConfig.class) public class MyTest { @Autowired private MyService myService; // 测试代码 } ``` 4. 使用注解 `@Test` 标记测试方法,并在方法内编写测试代码。 例如: ```java @RunWith(SpringRunner.class) @ContextConfiguration(classes = MyConfig.class) public class MyTest { @Autowired private MyService myService; @Test public void testMyService() { // 测试代码 } } ``` 这样配置后,你就可以编写和执行Spring单元测试了。注意,在进行单元测试时,可以使用Mockito等工具来模拟依赖的外部组件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值