Spring 整合 Junit4 进行单元测试

时间:2022-10-25 00:32:25

1. pom.xml 引入JAR依赖:

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.10.RELEASE</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.右键执行:

Spring 整合 Junit4 进行单元测试

 

 

 

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