zoukankan      html  css  js  c++  java
  • Java单元测试

    • Eclipse或STS中有可能需要手动在build path中增加相应版本的Junit依赖
    • JUnit 4
    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment= RANDOM_PORT)
    
    @RunWith(SpringJUnit4ClassRunner.class)  
    @ContextConfiguration(locations={"classpath:applicationContext.xml"})
    
    • JUnit 5

      • JUnit 5开始使用org.junit.jupiter及其子依赖包
        • 5.4版本以后才开始有org.junit.jupiter.api.Order、org.junit.jupiter.api.TestMethodOrder等类。如果pom.xml中不指定junit-jupiter-api的版本的话,有可能根据spring boot的版本(如2.1.7.RELEASE)找对应版本的JUnit 5,会没有这几个类。
      • 测试类(相当于一个suite?)
        • 命名通常以Test结尾
        • 如果是作为spring boot程序启动的,那么需要指明@ExtendWith(SpringExtension.class)
        • 指定配置文件:@TestPropertySource(locations = { "/application.properties" })
        • 指定需要初始化的配置类:@ContextConfiguration(classes = { XXXConfig.class, YYYConfig.class })
      • 测试方法
        • 命名通常以test开始
      @ExtendWith(SpringExtension.class)
      @TestPropertySource(locations = { "/application.properties" })
      @Import({EnvironmentConfig.class})
      @ContextConfiguration(classes = { XXXConfig.class, YYYConfig.class })
      @TestInstance(Lifecycle.PER_CLASS)
      public class XXXTest {
          private static final Logger logger = LoggerFactory.getLogger(XXX.class);
      
          @Autowired
          private XXXActions xxxActions;
      
          @BeforeAll
          public void setUp() throws Exception {
          }
      
          @AfterAll
          public void afterAll() throws Exception
          {
          }
      
          @Test
          public void testYYY() throws InterruptedException {
          }
      }
      
    • 结合Maven

      • mvn test执行所有测试用例
      • mvn test -Dtest=App2Test执行指定测试类
      • 通常需要使用maven-surefire-plugin插件
      <!-- Package as an executable jar -->
      <build>
          <plugins>
              <plugin>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-maven-plugin</artifactId>
              </plugin>
              <plugin>
                  <artifactId>maven-surefire-plugin</artifactId>
                  <version>2.22.0</version>
              </plugin>
          </plugins>
      </build>
      
  • 相关阅读:
    假期每日小结_2.2
    假期每日小结_2.1
    《新浪微博用户兴趣建模系统架构》阅读笔记
    《微博深度学习平台架构和实践》阅读笔记
    《亿级用户下的新浪微博平台架构》阅读笔记
    JavaScript中JSON的序列化和解析
    Servlet中@WebServlet("XXXX")注解无效,访问servlet报404错误
    数据卷(Data Volumes)
    Docker安装及基本命令
    springcloud服务配置中心
  • 原文地址:https://www.cnblogs.com/wyp1988/p/12125017.html
Copyright © 2011-2022 走看看