一.開發環境html
eclipse版本:4.6.1java
maven版本:3.3.3spring
junit版本:4.12apache
spring版本:4.1.5.RELEASEmvc
JDK版本:1.8.0_111eclipse
二.項目結構maven
圖單元測試
三.文件清單測試
pom.xmlui
- <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下載:點擊下載
來源:https://www.cnblogs.com/jpfss/p/8073091.html