天天看点

Springboot编写 junit4 测试

  1. 引入 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>
               
  2. 配置测试类能读取到配置文件 ,可以重新配置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>
               
  3. 新建 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);

    }

    }

  4. 表写所有要测试的类都要实现的 主类 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 {

    }

  5. 编写测试类 , 注意 点
    1. 测试类要 extends AbstractContextServiceTest
    2. 对要测试的类 后面加Test ,例如要测试 AlgoService类,那么测试类就叫 AlgoServiceTest
    3. 每个类都单独鞋测试类,形成好习惯
    package com.cxqz.service.handler;

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);
}
           

}

继续阅读