- 引入 mvn坐标
<!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency>
- 配置測試類能讀取到配置檔案 ,可以重新配置resource 也可以用正常的 ,配置如下
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> <!-- 如果沒有該配置,devtools不會生效 --> </configuration> </plugin> </plugins> <testResources> <testResource> <directory>src/main/resources</directory> <includes> <include>**/*.yml</include> </includes> <filtering>true</filtering> </testResource> </testResources>
-
建立 TestApplication 主啟動類
package com.cxqz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class,args);
}
}
-
表寫所有要測試的類都要實作的 主類 ContextConfiguration
package com.cxqz;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestApplication.class)
public class AbstractContextServiceTest {
}
- 編寫測試類 , 注意 點
- 測試類要 extends AbstractContextServiceTest
- 對要測試的類 後面加Test ,例如要測試 AlgoService類,那麼測試類就叫 AlgoServiceTest
- 每個類都單獨鞋測試類,形成好習慣
import cn.hutool.core.collection.CollectionUtil;
import com.cxqz.AbstractContextServiceTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Map;
public class AlgoServiceTest extends AbstractContextServiceTest {
@Autowired
private AlgoService algoService;
@Test
public void testSave() throws Exception {
Map sensorData = CollectionUtil.newHashMap();
sensorData.put("a","1");
String url = "http://192.168.21.46:8084/topic/print";
algoService.save(url,sensorData);
}
@Test
public void getDeviceByIdTest() throws Exception {
Map data = algoService.getDeviceById("小流水線1");
System.out.println(data);
}
}