Javaの空ではない文字列テストアサーション
1. 概要
特定のシナリオでは、指定されたStringが空であるかどうかをアサートする必要があります。 Javaでこのようなアサーションを行う方法はかなりあります。
このクイックチュートリアルのLet’s explore some of those test assertion techniques。
2. Mavenの依存関係
最初にいくつかの依存関係を取得する必要があります。 Mavenプロジェクトでは、次の依存関係をpom.xmlに追加できます。
junit
junit
4.12
org.hamcrest
hamcrest-core
1.3
org.apache.commons
commons-lang3
3.8
org.assertj
assertj-core
3.11.1
com.google.guava
guava
26.0-jre
3. JUnitを使用する
We’ll use the isEmpty method from the String class along with the Assert class from JUnit to verify whether a given String isn’t empty.入力Stringが空の場合、isEmptyメソッドはtrueを返すため、assertFalseメソッドと一緒に使用できます。
assertFalse(text.isEmpty());
または、次のものも使用できます。
assertTrue(!text.isEmpty());
Thought since text might be null,の別の方法は、assertNotEqualsメソッドを使用して等価性チェックを実行することです。
assertNotEquals("", text);
Or:
assertNotSame("", text);
JUnitアサーションhereに関する詳細なガイドを確認してください。
これらのアサーションはすべて、失敗するとAssertionError.を返します。
4. ハムクレストコアの使用
Hamcrestは、Javaエコシステムでの単体テストに一般的に使用されるマッチャーを提供するよく知られたフレームワークです。
We can make use of the Hamcrest CoreMatchers class for empty String checking:
assertThat(text, CoreMatchers.not(isEmptyString()));
isEmptyStringメソッドは、IsEmptyStringクラスで使用できます。
これは失敗した場合にもAssertionErrorを返しますが、出力はより有用です。
java.lang.AssertionError:
Expected: not an empty string
but: was ""
必要に応じて、文字列が空でもnullでもないことを確認するために、isEmptyOrNullStringを使用できます。
assertThat(text, CoreMatchers.not(isEmptyOrNullString()));
CoreMatchersクラスの他のメソッドについて学ぶには、thisの以前に公開された記事を読んでください。
5. Apache CommonsLangの使用
Apache Commons Langライブラリは、java.langAPI用のヘルパーユーティリティのホストを提供します。
StringUtils class offers a method that we can use to check for empty Strings:
assertTrue(StringUtils.isNotBlank(text));
失敗すると、単純なAssertionError.が返されます
Apache Commons Langを使用した文字列処理の詳細については、thisの記事をご覧ください。
6. AssertJの使用
AssertJはオープンソースであり、Javaテストで流暢で豊富なアサーションを作成するために使用されるコミュニティ主導のライブラリです。
メソッドAbstractCharSequenceAssert.isNotEmpty()は、実際のCharSequenceが空でないこと、またはin other words, that it is not null and has a length of 1 or moreが空でないことを確認します。
Assertions.assertThat(text).isNotEmpty()
失敗すると、これは出力を印刷します:
java.lang.AssertionError:
Expecting actual not to be empty
AssertJhereに関するすばらしい紹介記事があります。
7. Google Guavaを使用する
8. 結論
このクイックチュートリアルでは、指定されたStringが空であるかどうかをアサートする方法を見つけました。
いつものように、完全なコードスニペットはover on GitHubで利用できます。