日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

junit 测试 异常_使用JUnit规则测试预期的异常

發(fā)布時(shí)間:2023/12/3 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 junit 测试 异常_使用JUnit规则测试预期的异常 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

junit 測試 異常

這篇文章展示了如何使用JUnit測試預(yù)期的異常。 讓我們從我們要測試的以下類開始:

public class Person {private final String name;private final int age;/*** Creates a person with the specified name and age.** @param name the name* @param age the age* @throws IllegalArgumentException if the age is not greater than zero*/public Person(String name, int age) {this.name = name;this.age = age;if (age <= 0) {throw new IllegalArgumentException('Invalid age:' + age);}} }

在上面的示例中,如果人員的年齡不大于零,則Person構(gòu)造函數(shù)將引發(fā)IllegalArgumentException 。 有多種方法可以測試此行為:

這是我最喜歡的方法。 ExpectedException規(guī)則允許您在測試中指定期望的異常,甚至是異常消息。 如下所示:

import static org.hamcrest.Matchers.*; import static org.junit.Assert.*;import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException;public class PersonTest {@Rulepublic ExpectedException exception = ExpectedException.none();@Testpublic void testExpectedException() {exception.expect(IllegalArgumentException.class);exception.expectMessage(containsString('Invalid age'));new Person('Joe', -1);} }

如下面的代碼片段所示,您可以在@Test批注中指定預(yù)期的異常。 僅當(dāng)test方法拋出指定類的異常時(shí),測試才會(huì)通過。 不幸的是,您無法使用這種方法測試異常消息 。

@Test(expected = IllegalArgumentException.class) public void testExpectedException2() {new Person('Joe', -1); }

在引入注釋和規(guī)則之前,這是舊版本的JUnit使用的“傳統(tǒng)”方法。 將您的代碼包含在try-catch子句中,并測試是否引發(fā)了異常。 如果未引發(fā)異常,請不要忘記使測試失敗!

@Test public void testExpectedException3() {try {new Person('Joe', -1);fail('Should have thrown an IllegalArgumentException because age is invalid!');} catch (IllegalArgumentException e) {assertThat(e.getMessage(), containsString('Invalid age'));} }

參考: fahd.blog博客上的JCG合作伙伴 Fahd Shariff 用JUnit規(guī)則測試了預(yù)期的異常 。

翻譯自: https://www.javacodegeeks.com/2013/02/testing-expected-exceptions-with-junit-rules.html

junit 測試 異常

總結(jié)

以上是生活随笔為你收集整理的junit 测试 异常_使用JUnit规则测试预期的异常的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。