目录

Java assert 断言

目录

断言是 Java 编程语言中的一个语句,它使您能够测试您对程序的假设。例如,如果您编写一个计算粒子速度的方法,您可能会断言计算出的速度小于光速。

每个断言都包含一个布尔表达式,当断言执行时,您认为该表达式为真。如果不正确,系统将抛出错误。通过验证布尔表达式确实为真,断言证实了您对程序行为的假设,增加了您对程序没有错误的信心。

经验表明,在编程时编写断言是检测和纠正错误的最快和最有效的方法之一。作为一个额外的好处,断言用于记录程序的内部工作,增强可维护性。

1
2
3
4
5
org.junit.jupiter.api.Assertions
// org.assertj:assertj-core
org.assertj.core.api.Assertions
// org.springframework:spring-core
org.springframework.util.Assert

Truth

Fluent assertions for Java and Android

1
2
3
4
5
6
<dependency>
  <groupId>com.google.truth</groupId>
  <artifactId>truth</artifactId>
  <version>1.1.3</version>
  <scope>test</scope>
</dependency>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;

// for assertions on Java 8 types (Streams and java.util.Optional)
import static com.google.common.truth.Truth8.assertThat;


String string = "awesome";
assertThat(string).startsWith("awe");
assertWithMessage("Without me, it's just aweso")
    .that(string)
    .contains("me");

Iterable<Color> googleColors = googleLogo.getColors();
assertThat(googleColors)
    .containsExactly(BLUE, RED, YELLOW, BLUE, GREEN, RED)
    .inOrder();

Hamcrest

1
2
3
4
5
6
7
<!-- https://mvnrepository.com/artifact/org.hamcrest/hamcrest -->
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest</artifactId>
    <version>2.2</version>
    <scope>test</scope>
</dependency>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat; 
import static org.hamcrest.Matchers.*;

public class BiscuitTest {
  @Test 
  public void testEquals() { 
    Biscuit theBiscuit = new Biscuit("Ginger"); 
    Biscuit myBiscuit = new Biscuit("Ginger"); 
    assertThat(theBiscuit, equalTo(myBiscuit)); 
  } 
}
// Writing custom matchers
import org.hamcrest.Description; 
import org.hamcrest.Matcher; 
import org.hamcrest.TypeSafeMatcher;

public class IsNotANumber extends TypeSafeMatcher {

  @Override 
  public boolean matchesSafely(Double number) { 
    return number.isNaN(); 
  }

  public void describeTo(Description description) { 
    description.appendText("not a number"); 
  }

  public static Matcher notANumber() { 
    return new IsNotANumber(); 
  }
}

@Test
public void testSquareRootOfMinusOneIsNotANumber() { 
  assertThat(Math.sqrt(-1), is(notANumber())); 
}