1. 程式人生 > 實用技巧 >spring整合測試

spring整合測試

一、pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>org.example</groupId>
    <artifactId>A02spring</artifactId>
    <version>1.0
-SNAPSHOT</version> <dependencies> <!--https://mvnrepository.com/artifact/org.springframework/spring-context--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2
.8.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2
.8.RELEASE</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>

二、測試類

/*
@ContextConfiguration:指定spring配置
    屬性:
        classes:指定配置類
        locations:指定配置檔案,要加關鍵字classpath:
*/
@RunWith(SpringJUnit4ClassRunner.class)//替換junit的main方法,使用spring提供的方法
@ContextConfiguration(classes = SpringConfig.class)
public class MySpringTest {
    @Autowired
    private Grade grade;

    @Test
    public void test01() {
        grade.studentMethod();
    }
}