一.开发环境
eclipse版本:4.6.1
maven版本:3.3.3
junit版本:4.12
spring版本:4.1.5.RELEASE
JDK版本:1.8.0_111
二.项目结构
图
三.文件清单
pom.xml
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>springJunit</groupId>
- <artifactId>springJunit</artifactId>
- <version>1.0</version>
- <packaging>war</packaging>
- <properties>
- <!-- spring版本号 -->
- <spring.version>4.1.5.RELEASE</spring.version>
- <!-- junit版本号 -->
- <junit.version>4.12</junit.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>${junit.version}</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
- </project>
JunitTest.java
- package com.dqiang;
- public interface JunitTest {
- public String sayHelloWorld(String word);
- }
JunitTestImpl.java
- package com.dqiang.impl;
- import org.springframework.stereotype.Service;
- import com.dqiang.JunitTest;
- @Service
- public class JunitTestImpl implements JunitTest {
- public String sayHelloWorld(String word) {
- return "hello->" + word;
- }
- }
JTest.java
- package springJunit;
- 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;
- import com.dqiang.JunitTest;
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations = { "classpath:springmvc.xml" })
- public class JTest {
- @Autowired
- private JunitTest junitTest;
- @Test
- public void sayHelloWorld() {
- String result = junitTest.sayHelloWorld("junit Test");
- System.out.println(result);
- }
- }
说明:
@RunWith 使用RunWith注解改变JUnit的默认执行类,并实现自已的Listener在平时的单元测试,如果不使用RunWith注解,那么JUnit将会采用默认的执行类Suite执行。
@ContextConfiguration 可以通过该属性手工指定 Spring 配置文件所在的位置,可以指定一个或多个 Spring 配置文件。
Demo下载:点击下载