junit断言

JUnit Assertions allows us to write effective test methods. JUnit 5 is the latest version and JUnit Jupiter provides a lot of assertions to assert different types of statements.

JUnit断言允许我们编写有效的测试方法。 JUnit 5是最新版本,JUnit Jupiter提供了许多断言来断言不同类型的语句。

JUnit断言 (JUnit Assertions)

JUnit Jupiter org.junit.jupiter.api.Assertions class provides a collection of utility methods to use in our test code. All these methods are static, so we can import them and write fluent code. Almost all of these methods are overloaded to support primitives, objects, Collections, Stream, Arrays etc.

JUnit Jupiter org.junit.jupiter.api.Assertions类提供了可在我们的测试代码中使用的实用程序方法的集合。 所有这些方法都是静态的,因此我们可以导入它们并编写流畅的代码。 几乎所有这些方法都被重载以支持原语,对象,集合,流,数组等。

import static org.junit.jupiter.api.Assertions.*;

Let’s look at some of the important JUnit assert methods with an example.

让我们通过示例来看一些重要的JUnit assert方法。

失败() (fail())

This is used to fail a test, it’s useful when your test method is work in progress and you want to indicate that by fail-fast your test. There are many overloaded fail() methods, let’s look at some of them.

这用于使测试失败,当您的测试方法正在开发中并且您想通过快速失败测试来表明这一点时,这很有用。 有很多重载的fail()方法,让我们看一下其中的一些方法。

@Test
@DisplayName("This will Fail, don't worry!")
void test_fail() {fail();fail("Not yet implemented");fail(() -> {return "Not yet implemented";});fail("Not Yet Implemented", new RuntimeException("Explicitly Failed"));fail(new RuntimeException("Explicitly Failed"));}

We can provide custom failure message and specify the cause of failure.

我们可以提供自定义失败消息并指定失败原因。

assertNull()和assertNotNull() (assertNull() and assertNotNull())

These methods are used to check if the specified object is null or not. We can also specify custom failure message.

这些方法用于检查指定的对象是否为null。 我们还可以指定自定义失败消息。

@Test
@DisplayName("assertNull Examples")
void test_assertNull() {assertNull(null);//assertNull(new Object(), "assertNull Fail Message");
}@Test
@DisplayName("assertNotNull Examples")
void test_assertNotNull() {assertNotNull(new Object());//assertNotNull(null, "assertNotNull Fail Message");
}

assertSame()和assertNotSame() (assertSame() and assertNotSame())

These methods are used to assert that expected and actual elements are same or not. JUnit uses == operator for these methods to check if they are referring to same object or not.

这些方法用于断言预期元素和实际元素是否相同。 JUnit对这些方法使用==运算符来检查它们是否引用了同一对象。

@Test
@DisplayName("assertSame Examples")
void test_assertSame() {assertSame("Hi", "Hi");// this will fail// assertSame("Hi", new String("Hi"), "My Failure Message");}@Test
@DisplayName("assertNotSame Examples")
void test_assertNotSame() {assertNotSame("Hi", "Hello");// this will fail//assertNotSame("Hi", "Hi", "assertNotSame Failure Message");}

assertTrue()和assertFalse() (assertTrue() and assertFalse())

Asserts that the supplied condition is true or false.

断言所提供的条件为truefalse

@Test
@DisplayName("assertTrue Examples")
void test_assertTrue() {assertTrue(3 > 0);assertTrue(() -> {return true;});assertTrue(3 > 0, "assertTrue fail message");assertTrue(3 > 0, () -> {return "assertTrue fail message";});assertTrue(() -> {return true;}, "assertTrue fail message");assertTrue(() -> {return true;}, () -> {return "assertTrue fail message";});
}@Test
@DisplayName("assertFalse Examples")
void test_assertFalse() {assertFalse(3 < 0);assertFalse(() -> {return false;});assertFalse(3 < 0, "assertFalse fail message");assertFalse(3 < 0, () -> {return "assertFalse fail message";});assertFalse(() -> {return false;}, "assertFalse fail message");assertFalse(() -> {return false;}, () -> {return "assertFalse fail message";});
}

assertEquals()和assertNotEquals() (assertEquals() and assertNotEquals())

These two methods are used to assert that expected and actual objects are equal or not. They use equals() method of the object to check equality.

这两种方法用于断言预期对象和实际对象是否相等。 他们使用对象的equals()方法检查相等性。

@Test
@DisplayName("assertEquals Examples")
void test_assertEquals() {assertEquals(10, 10);assertEquals(true, true, "assertEquals Failure Message");assertEquals("Hi", new String("Hi"));assertEquals(new File("test"), new File("test"));
}@Test
@DisplayName("assertNotEquals Examples")
void test_assertNotEquals() {assertNotEquals(10, 100);assertNotEquals(true, false, "assertEquals Failure Message");assertNotEquals("Hi", new String("Hello"));assertNotEquals(new File("test"), new File("test1"));
}

assertArrayEquals() (assertArrayEquals())

Asserts that expected and actual arrays are deeply equal. The arrays elements are matched index by index.

断言期望数组和实际数组完全相等。 数组元素按索引匹配。

@Test
@DisplayName("assertArrayEquals Examples")
void test_assertArrayEquals() {String[] s1 = { "A", "B" };String[] s2 = { "A", "B" };assertArrayEquals(s1, s2);assertArrayEquals(s1, s2, "My Custom Failure Message");
}

assertIterableEquals() (assertIterableEquals())

This method is used for iterables to check if they are equal or not. Note that the underlying implementation can be different. The elements are matched index by index for equality.

此方法用于可迭代项以检查它们是否相等。 请注意,基础实现可以不同。 元素通过索引匹配以相等。

@Test
@DisplayName("assertIterableEquals Examples")
void test_assertIterableEquals() {List<String> l1 = new ArrayList<>(Arrays.asList("A", "B"));List<String> l2 = new LinkedList<>(Arrays.asList("A", "B"));assertIterableEquals(l1, l2);assertIterableEquals(l1, l2, "Custom Failure Message");
}

assertThrows() (assertThrows())

Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.

断言所提供的可执行文件的执行将引发ExpectedType的异常并返回该异常。

If no exception is thrown, or if an exception of a different type is thrown, this method will fail.

如果没有引发异常,或者引发了其他类型的异常,则此方法将失败。

This method follows inheritance hierarchy, so the assert will pass if the expected type is Exception and actual is RuntimeException.

此方法遵循继承层次结构,因此,如果期望的类型为Exception而实际类型为RuntimeException ,则声明将通过。

@Test
@DisplayName("assertThrows Examples")
void test_assertThrows() {assertThrows(RuntimeException.class, () -> {throw new RuntimeException();});assertThrows(Exception.class, () -> {throw new RuntimeException();});// this will fail// assertThrows(IOException.class, () -> {throw new RuntimeException();});// assertThrows(IOException.class, () -> {throw new RuntimeException();}, "assertThrows Failure Message");
}

assertDoesNotThrow() (assertDoesNotThrow())

Asserts that execution of the supplied executable does not throw any kind of exception. This method takes org.junit.jupiter.api.function.Executable instance as argument. Executable is a functional interface that can be used to implement any generic block of code that potentially throws a Throwable.

断言所提供的可执行文件的执行不会引发任何异常。 此方法以org.junit.jupiter.api.function.Executable实例作为参数。 可执行文件是一个功能性接口 ,可用于实现可能抛出Throwable的任何通用代码块。

class MyExecutable implements Executable {@Overridepublic void execute() throws Throwable {System.out.println("Hello There!");}}

We can use lambda expressions to create Executable if we are not planning to reuse it.

如果我们不打算重用它,则可以使用lambda表达式创建Executable。

@Test
@DisplayName("assertDoesNotThrow Examples")
void test_assertDoesNotThrow() {assertDoesNotThrow(new MyExecutable());assertDoesNotThrow(new MyExecutable(), "assertDoesNotThrow custom message");
}

assertAll() (assertAll())

Asserts that all supplied executables do not throw exceptions. We can pass Array, Stream or a Collection of Executable objects.

断言所有提供的可执行文件都不会引发异常。 我们可以传递数组, 流或Executable对象的集合。

@Test
@DisplayName("assertAll Examples")
void test_assertAll() {assertAll(Arrays.asList(new MyExecutable()));assertAll(new MyExecutable());assertAll(Stream.of(new MyExecutable()));//assertAll("My Executables Heading Error Message", () -> {throw new Exception("Hi");});
}

assertTimeout() (assertTimeout())

Asserts that execution of the supplied executable completes before the given timeout is exceeded.

声明所提供的可执行文件的执行在超过给定的超时之前完成。

The executable will be executed in the same thread as that of the calling code. Consequently, execution of the executable will not be preemptively aborted if the timeout is exceeded.

该可执行文件将在与调用代码相同的线程中执行。 因此,如果超过超时时间,可执行文件的执行将不会被抢先中止。

@Test
@DisplayName("assertTimeout Examples")
void test_assertTimeout() {assertTimeout(Duration.ofSeconds(1), new MyExecutable());assertTimeout(Duration.ofSeconds(3), () -> {Thread.sleep(2000);System.out.println("Done");});// this will fail/*assertTimeout(Duration.ofNanos(1), () -> {Thread.sleep(20);System.out.println("Done");}, "assertTimeout Failure Message: Too less time to execute");*/
}

assertTimeoutPreemptively() (assertTimeoutPreemptively())

Asserts that execution of the supplied executable completes before the given timeout is exceeded.

声明所提供的可执行文件的执行在超过给定的超时之前完成。

The executable will be executed in a different thread than that of the calling code. Furthermore, execution of the executable will be preemptively aborted if the timeout is exceeded.

该可执行文件将在与调用代码不同的线程中执行。 此外,如果超过了超时时间,可执行文件的执行将被抢先中止。

@Test
@DisplayName("assertTimeoutPreemptively Examples")
void test_assertTimeoutPreemptively() {assertTimeoutPreemptively(Duration.ofSeconds(1), new MyExecutable());assertTimeoutPreemptively(Duration.ofMillis(100), () -> System.out.println("Hello There"));// this will timeout for sure// assertTimeoutPreemptively(Duration.ofNanos(1), () -> System.out.println("Hello There"));/*assertTimeoutPreemptively(Duration.ofSeconds(1), () -> {throw new RuntimeException("");});*/assertTimeoutPreemptively(Duration.ofSeconds(1), new MyExecutable(),"MyExecutable didn't completed within 1 second");assertTimeoutPreemptively(Duration.ofSeconds(1), new MyExecutable(), () -> {return "MyExecutable didn't completed within 1 second";});/*assertTimeoutPreemptively(Duration.ofSeconds(2), () -> {throw new RuntimeException("");}, "MyExecutable didn't completed within 2 second");*/
}

JUnit断言示例测试 (JUnit Assert Examples Test)

Below image shows the JUnit test results view in Eclipse when the test class was executed.

下图显示了执行测试类时Eclipse中的JUnit测试结果视图。

摘要 (Summary)

JUnit Jupiter provides a lot of assertions to help us write fluent test code. It’s always a good idea to import these assertion static methods and then write clean code.

JUnit Jupiter提供了许多断言来帮助我们编写流畅的测试代码。 导入这些断言静态方法,然后编写简洁的代码始终是一个好主意。

GitHub Repository.GitHub存储库中检出完整的代码。

翻译自: https://www.journaldev.com/21681/junit-assertions

junit断言

junit断言_JUnit断言相关推荐

  1. JUnit的各种断言

    JUnit为我们提供了一些辅助函数,他们用来帮助我们确定被测试的方法是否按照预期的效果正常工作,通常,把这些辅助函数称为断言.下面我们来介绍一下JUnit的各种断言. 断言是编写测试用例的核心实现方式 ...

  2. JUnit测试常用断言

    JUnit主要使用断言来进行单元测试,常见的断言如表中所示: 断言 功能 assertEquals([String message], expected value, actual value) 检查 ...

  3. jmeter响应断言使用_十二、Jmeter断言-响应断言、Json断言和Beanshell断言

    所谓断言,就是检查接口的返回是否符合预期. 自动化测试脚本,如果断言做的不好,就好比测试用例不写预期结果,因此我认为断言是最重要一部分. 关于如何做好断言,我觉得要做到:要断言的内容一定是唯一的,每个 ...

  4. Jmeter断言-响应断言

    1:Jmeter断言-响应断言 1.1:添加线程组 1.2:添加http请求 1.3:在http请求下添加"响应断言" 1.4:添加查看结果树和Debug取样器 1:断言成功的结果 ...

  5. Jmeter断言-所有断言讲解

    Jmeter断言-所有断言讲解 jmeter中有个元件叫做断言(Assertion),它的作用和loadrunner中的检查点类似: 用于检查测试中得到的响应数据等是否符合预期,用以保证性能测试过程中 ...

  6. 【接口测试基础】第八篇 | PostMan常用断言及断言的工作原理

    Postman常用断言 1.断言响应状态码 Status code: Code is 200 步骤: 1.在Tests标签中,选中Status Code:code is 200,生成对应代码 2.适当 ...

  7. 验证断言(立即断言并行断言)

    目录 1.何为断言 2.断言的作用: 3.断言的种类 3.1立即断言 3.2并发断言 4.断言层次结构 4.1 sequence 序列 4.2 property 序列 5.sequence和prope ...

  8. 性能测试——jmeter接口测试复习——断言——响应断言

    {"ret":200,"data":{"err_code":0,"err_msg":""," ...

  9. junit单元测试断言_简而言之,JUnit:单元测试断言

    junit单元测试断言 简而言之,本章涵盖了各种单元测试声明技术. 它详细说明了内置机制, Hamcrest匹配器和AssertJ断言的优缺点 . 正在进行的示例扩大了主题,并说明了如何创建和使用自定 ...

最新文章

  1. weblogic 配置mysql数据源Cannot load driver class: com.mysql.jdbc.Driver的问题
  2. python协程框架_[记录]python的简单协程框架(回调+时间循环+select)
  3. android常见错误-Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE
  4. spark内核回顾思考 RDD
  5. Android之关于电话录音原理,目前的方法还是只能录MIC
  6. NSLog的常用格式说明小释
  7. 2018科来杯WriteUp
  8. matlab二维函数的傅立叶变换,二维傅里叶变换和滤波(Two
  9. 年近30,半失业状态:定制化,正在拖垮年轻人
  10. 第7-3课:K 最邻近算法(KNN)与手写数字识别
  11. Cmd Markdown
  12. Linux网络配置后无法正常上网
  13. 最严“22条措施”打击市场乱象 云南旅游“浴火重生”
  14. 怎么把收藏夹变成html文件,用Delphi将IE收藏夹导出为HTML文件
  15. 洛谷P1150 Peter的烟(逻辑建模)
  16. 计算机网络基带和宽带,基带信号和宽带信号
  17. Python爬虫 爬取标题及内容
  18. 【踩坑专栏】 Cannot access aliyun () in offline mode and the artifact sso-demo:parent:pom:1.0-SNAPSHOT has
  19. iOS 视频拍摄与压缩
  20. 计算机二级宝典几个人用,计算机二级宝典

热门文章

  1. Oracle增加自增长列
  2. [转载] python数学编程书推荐_图书推荐:《Python数学编程》
  3. [转载] 使用python 中的numpy创建数组
  4. 单工、半双工、双工通信详解
  5. 用框架名唬人谁都会,那你知道Web开发模式吗?——莫问前程莫装逼
  6. Lua中local变量和非local变量的区别
  7. HTML5新增的表单类型
  8. idea android 开发
  9. V-rep学习笔记:机器人逆运动学数值解法(Damped Least Squares / Levenberg-Marquardt Method)...
  10. 两百个jQuery插件集合