1、导入依赖jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.0.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<scope>test</scope>表示打包时不会加入这些jar包
2、注解
- @RunWith:用于指定Junit运行环境,时Junit提供给其他框架测试环境接口扩展,为了便于使用spring的依赖注入,spring提供了SpringJunit4ClassRunner作为Junit测试环境
- @ContextConfiguration导入配置文件,支持xml,JavaConfig配置类
具体配置代码如下:
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.neuedu.service.TestService;
import com.neuedu.test.Appconfig;
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations= {"classpath:applicationContext.xml"})
@ContextConfiguration(classes=Appconfig.class)
public class TestController {
@Autowired
private TestService testService;
public void setTestService(TestService testService) {
this.testService = testService;
}
@Test
public void test() {
testService.test();
}
}