首页 > 代码库 > Spring 整合 Junit4 进行单元测试

Spring 整合 Junit4 进行单元测试

1. pom.xml 引入JAR依赖:

<dependency>    <groupId>junit</groupId>    <artifactId>junit</artifactId>    <version>${junit.version}</version>    <scope>test</scope></dependency><dependency>    <groupId>org.testng</groupId>    <artifactId>testng</artifactId>    <version>${testng.version}</version>    <scope>test</scope></dependency><dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-test</artifactId>    <version>${spring.version}</version>    <scope>test</scope></dependency>

 

2.编写测试用例:

@RunWith(SpringJUnit4ClassRunner.class)  注解让测试运行于Spring测试环境。

@ContextConfiguration注解加载的是Spring的配置文件。

@Test 注解放在需要测试执行的方法上。

package com.phpdragon;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/** * Created by phpdragon on 2017/4/20. */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = "/META-INF/spring/dubbo-provider.xml")public class AtresiaTest {    @Test    public void test0() {        System.out.println("test0");    }    @Test    public void test1() {        class TestObject implements Runnable {            public void run(){                try {                    Thread.sleep(1000);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }        long timeTasks = 0;        AtresiaDemo demo = new AtresiaDemo();        try {            timeTasks = demo.timeTasks(4,new TestObject());        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println("timeTasks :"+ timeTasks);    }}

 

3.右键执行:

技术分享

 

 

 

PS:http://www.cnblogs.com/wangtj-19/p/5821725.html

Spring 整合 Junit4 进行单元测试