霍格沃兹测试开发学社
ceshiren.com
assertEquals
实例assertTrue
实例package cn.assertionDemo;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class AssertTrueDemo {
@Test
void testAssertTrueExpression() {
// 断言对象是表达式
assertTrue(3 > 1);
}
@Test
void testAssertTrueBoolean() {
// 断言对象是布尔类型
assertTrue(true);
}
}
assertNotNull
实例package hogwarts;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class AssertNotNullDemo {
@Test
void testAssertNotNullTrue() {
// 断言对象如果不是null则返回true
assertNotNull("hogwarts");
}
@Test
void testAssertNotNullFalse() {
// 断言对象如果是null则返回false
assertNotNull(null);
}
}
assertAll
实例package cn.assertionDemo;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class AssertAllDemo {
@Test
void testAssertAll() {
// 分组断言
assertAll("All",
() -> assertEquals(2, 1 + 1),
() -> assertEquals(4, 2 + 2)
);
}
}
assertTimeout
实例package cn.assertionDemo;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import static java.lang.Thread.sleep;
import static org.junit.jupiter.api.Assertions.assertTimeout;
public class AssertTimeoutDemo {
@Test
void testAssertTimeout() {
// 超时断言
assertTimeout(Duration.ofSeconds(3), ()->{
sleep(2000);
});
}
}
assertThrows
实例package cn.assertionDemo;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class AssertThrowsDemo {
void fn(int a, int b){
System.out.println(a / b);
}
@Test
void testAssertThrows() {
// 异常断言
assertThrows(ArithmeticException.class, () -> fn(1, 0));
}
}