当前位置:   article > 正文

Gradle中使用Junit5做单元测试备忘_gradle junit5

gradle junit5

配制build.gradle

  1. dependencies {
  2. testImplementation(platform('org.junit:junit-bom:5.7.2'))
  3. testImplementation('org.junit.jupiter:junit-jupiter')
  4. }
  5. test {
  6. useJUnitPlatform()
  7. testLogging {
  8. events "passed", "skipped", "failed"
  9. }
  10. }

测试示例

  1. import org.junit.jupiter.api.DisplayName;
  2. import org.junit.jupiter.api.Test;
  3. import java.time.Duration;
  4. import static org.junit.jupiter.api.Assertions.assertAll;
  5. import static org.junit.jupiter.api.Assertions.assertEquals;
  6. import static org.junit.jupiter.api.Assertions.assertThrows;
  7. import static org.junit.jupiter.api.Assertions.assertTimeout;
  8. @DisplayName("Junit5单元测试示例")
  9. public class Junit5Test {
  10. @Test
  11. @DisplayName("DisplayName注解测试")
  12. void testWithDisplayName() {
  13. }
  14. @Test
  15. @DisplayName("Assertions.assertEquals测试")
  16. void testAssertEquals(){
  17. String name = "hello junit5";
  18. assertEquals("hello junit5",name,"name not same");
  19. }
  20. @Test
  21. @DisplayName("Assertions.assertAll测试")
  22. void testAssertAll(){
  23. assertAll("判断是否全部相同",
  24. () -> assertEquals("hello", "hello"),
  25. () -> assertEquals("world", "world")
  26. );
  27. }
  28. @Test
  29. @DisplayName("Assertions.assertThrows测试")
  30. void exceptionTesting() {
  31. Exception exception = assertThrows(ArithmeticException.class, ()->{
  32. System.out.println(1/0);
  33. });
  34. assertEquals("/ by zero", exception.getMessage());
  35. }
  36. @Test
  37. @DisplayName("Assertions.assertTimeout测试")
  38. void timeoutExceeded() {
  39. assertTimeout(Duration.ofMillis(10), () -> {
  40. Thread.sleep(9);
  41. });
  42. }
  43. }

参考来源

https://junit.org/junit5/docs/current/user-guide/

https://github.com/junit-team/junit5-samples/tree/r5.7.2/junit5-jupiter-starter-gradle

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/68465
推荐阅读
  

闽ICP备14008679号