1.除了spring相关依赖,额外引入spring-test相关的依赖
增加spring-test依赖和junit依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId >
<artifactId>junit</artifactId >
<version>${junit.version}</version >
<scope>test</scope >
</dependency>
2.创建spring-test单元测试基类,完成spring-test相关配置,方便业务系统直接使用
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration(locations = { "classpath*:applicationContext-test.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class BaseTest {
@Test
public void test() {
System.out.println("如果看到此行,说明单元测试环境搭建成功!");
}
}
扩展:
如果需要启用spring的profile机制,可以在BaseTest类上增加@ActiveProfiles注解;
如果需要测试中涉及到数据库更新操作,但希望不修改测试库,可以BaseTest类上增加@Transactional注解,让测试事务回滚。
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
/**
* 增加@ActiveProfiles,启用profile
* 增加@Transactional,测试事务自动回滚
*/
@ActiveProfiles(profiles = {"test"})
@ContextConfiguration(locations = { "classpath*:applicationContext-test.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
public class BaseTest {
@Test
public void test() {
System.out.println("如果看到此行,说明单元测试环境搭建成功!");
}
}
3.业务测试类只需要继承该基类,在单元测试方法上加@Test注解,即可很方便的进行单元测试。
import org.junit.Test;
import com.ipr.user.test.SpringConfigTest;
public class UserServiceTest extends BaseTest {
@Test
public void testGetUserByUsername() {
System.out.println("这是具体的单元测试");
}
}