Spring的学习(三)——单元测试
程序员文章站
2022-06-05 11:28:04
...
在Spring中使用单元测试需要引入Spring单元测试模块:
加入Junit、Spring-test
然后在测试对的类上加上注解:@RunWith(SpringJUnit4ClassRunner.class)
然后再加上注解:@ContextConfiguration(classes=配置类.class)
比如我们将上一篇当中的程序来进行测试:https://blog.csdn.net/qq_41061437/article/details/82701967
maven配置文件:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.19.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.19.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
import org.springframework.stereotype.Component;
@Component
public class CompactDisc {
public CompactDisc() {
System.out.println("CompactDisc无参构造函数");
}
public void play(){
System.out.println("正在播放音乐");
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class CDPlayer {
private CompactDisc cd;
public CDPlayer() {
System.out.println("CDPlayer无参构造");
}
@Autowired
public CDPlayer(CompactDisc cd) {
this.cd = cd;
System.out.println("CDPlayer的有参构造函数");
}
public void play(){
cd.play();
}
}
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class AppConfig {
}
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;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=AppConfig.class)
public class AppTest {
@Autowired
private CDPlayer player;
@Test
public void testplay(){
player.play();
}
}
我们对比一下,发现将上一篇的App类写成AppTest类,即测试类。
首先就是在AppTest类上多了两个注解:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=AppConfig.class)
然后去掉了加载配置文件的代码:
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
因为使用了@ContextConfiguration(classes=AppConfig.class)注解,此注解自动帮我们加载了配置文件。
然后不再使用getBean方法来获取Spring容器中的实例对象,只需要在代码里面写private CDPlayer player;的引用,然后加上注解@Autowired就可以自动帮我们获取实例以及实例之间的依赖关系。