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>
    
原文地址:https://www.cnblogs.com/wyp1988/p/12125017.html