- Ожидаемое исключение JUnit 5
- 1. Assertions API assertThrows ()
- 1.1. Синтаксис
- 1.2. Вывод теста
- 2. Ожидаемое исключение генерируемое в тесте
- 3. Сгенерировано исключение другого типа, или не сгенерировано исключение
- Java junit assert exception
- Assert
- assertTrue
- assertTrue
- assertFalse
- assertFalse
- assertEquals
- assertEquals
- assertNotEquals
- assertNotEquals
- assertNotEquals
- assertNotEquals
- assertNotEquals
- assertNotEquals
- assertNotEquals
- assertArrayEquals
- assertArrayEquals
- assertArrayEquals
- assertArrayEquals
- assertArrayEquals
- assertArrayEquals
- assertArrayEquals
- assertArrayEquals
- assertArrayEquals
- assertArrayEquals
- assertArrayEquals
- assertArrayEquals
- assertArrayEquals
- assertArrayEquals
- assertArrayEquals
- assertArrayEquals
- assertArrayEquals
- assertArrayEquals
- assertEquals
- assertEquals
- assertNotEquals
- assertEquals
- assertEquals
- assertEquals
- assertEquals
- assertEquals
- assertEquals
- assertNotNull
- assertNotNull
- assertNull
- assertNull
- assertSame
- assertSame
- assertNotSame
- assertNotSame
- assertEquals
- assertEquals
- assertThat
- assertThat
- assertThrows
Ожидаемое исключение JUnit 5
Это продолжение туториала по JUnit 5. Введение опубликовано здесь.
В JUnit 5, чтобы написать тестовый код, который, как ожидается, вызовет исключение, мы должны использовать Assertions.assertThrows().
В данном примере ожидается, что тестовый код в комментированном блоке вызовет исключение типа ApplicationException .
Использование Assertions.assertThrows()
Оглавление
Assertions API assertThrows ().
Ожидаемое исключение генерируется в тесте.
Сгенерировано исключение другого типа, или не сгенерировано исключение
1. Assertions API assertThrows ()
1.1. Синтаксис
Метод assertThrows() утверждает, что выполнение прилагаемого исполняемого блока или лямбда — выражения вызывает исключение типа expectedType . Это перегруженный метод, который принимает следующие параметры.
expectedType — ожидается, что тестовый код вызовет исключение этого типа.
message — если исполняемый код не вызывает никаких исключений, это сообщение будет напечатано вместе с результатом FAIL.
messageSupplier — сообщение будет извлечено из него в случае неудачи теста.
1.2. Вывод теста
Если в блоке не было генерировано исключение, executable , то assertThrows() вернет FAIL .
Если выбрасывается исключение другого типа, assertThrows() будет FAIL .
Если блок кода вызывает исключение класса, который является подтипом исключения expectedType , только тогда assertThrows() вернет PASS .
Например, если мы ожидаем, IllegalArgumentException и тест выдает ошибку NumberFormatException, тогда и вывод теста будет PASS потому что NumberFormatException расширяет класс IllegalArgumentException.
Кроме того, если мы передадим Exception.class в качестве ожидаемого типа исключения, любое исключение, выброшенное из исполняемого блока, сделает результат assertion равным PASS , поскольку Exception является супертипом для всех исключений.
2. Ожидаемое исключение генерируемое в тесте
Ниже приведен очень простой тест, который ожидает, что исключение NumberFormatException будет сгенерировано при выполнении предоставленного блока кода.
Оба теста выдают PASS
В тесте testExpectedException , исполняемый код Integer.parseInt(«One») генерирует исключение NumberFormatException, если аргумент метода не является допустимым текстовым представлением числа. Метод assertThrows() ожидает это исключение, так что результат теста PASS .
В тесте testExpectedExceptionWithParentType , мы выполняем тот же код, но на этот раз мы принимаем исключение IllegalArgumentException , родительское для NumberFormatException . Этот тест тоже проходит.
3. Сгенерировано исключение другого типа, или не сгенерировано исключение
Если исполняемый код вызывает исключение любого другого типа, то результат теста будет FAIL .
И даже если исполняемый код не вызывает никаких исключений, результат теста тоже будет FAIL .
Например, в приведенном ниже примере «1» это допустимое число, поэтому исключение не возникает. Этот тест завершится ошибкой с сообщением в консоли.
В этом посте мы узнали, как написать тест, ожидающий возникновение исключений. Эти тесты полезны при тестировании кода, написанного в блоках catch.
Java junit assert exception
A set of assertion methods useful for writing tests. Only failed assertions are recorded. These methods can be used directly: Assert.assertEquals(. ) , however, they read better if they are referenced through static import:
Constructor Summary | |
---|---|
protected | Assert () Protect constructor since it is a static only class |
Method Summary | ||
---|---|---|
static void | assertArrayEquals (boolean[] expecteds, boolean[] actuals) Asserts that two boolean arrays are equal. | |
static void | assertArrayEquals (byte[] expecteds, byte[] actuals) Asserts that two byte arrays are equal. | |
static void | assertArrayEquals (char[] expecteds, char[] actuals) Asserts that two char arrays are equal. | |
static void | assertArrayEquals (double[] expecteds, double[] actuals, double delta) Asserts that two double arrays are equal. | |
static void | assertArrayEquals (float[] expecteds, float[] actuals, float delta) Asserts that two float arrays are equal. | |
static void | assertArrayEquals (int[] expecteds, int[] actuals) Asserts that two int arrays are equal. | |
static void | assertArrayEquals (long[] expecteds, long[] actuals) Asserts that two long arrays are equal. | |
static void | assertArrayEquals (Object[] expecteds, Object[] actuals) Asserts that two object arrays are equal. | |
static void | assertArrayEquals (short[] expecteds, short[] actuals) Asserts that two short arrays are equal. | |
static void | assertArrayEquals (String message, boolean[] expecteds, boolean[] actuals) Asserts that two boolean arrays are equal. | |
static void | assertArrayEquals (String message, byte[] expecteds, byte[] actuals) Asserts that two byte arrays are equal. | |
static void | assertArrayEquals (String message, char[] expecteds, char[] actuals) Asserts that two char arrays are equal. | |
static void | assertArrayEquals (String message, double[] expecteds, double[] actuals, double delta) Asserts that two double arrays are equal. | |
static void | assertArrayEquals (String message, float[] expecteds, float[] actuals, float delta) Asserts that two float arrays are equal. | |
static void | assertArrayEquals (String message, int[] expecteds, int[] actuals) Asserts that two int arrays are equal. | |
static void | assertArrayEquals (String message, long[] expecteds, long[] actuals) Asserts that two long arrays are equal. | |
static void | assertArrayEquals (String message, Object[] expecteds, Object[] actuals) Asserts that two object arrays are equal. | |
static void | assertArrayEquals (String message, short[] expecteds, short[] actuals) Asserts that two short arrays are equal. | |
static void | assertEquals (double expected, double actual) Deprecated. Use assertEquals(double expected, double actual, double delta) instead | |
static void | assertEquals (double expected, double actual, double delta) Asserts that two doubles are equal to within a positive delta. | |
static void | assertEquals (float expected, float actual, float delta) Asserts that two floats are equal to within a positive delta. | |
static void | assertEquals (long expected, long actual) Asserts that two longs are equal. | |
static void | assertEquals (Object[] expecteds, Object[] actuals) Deprecated. use assertArrayEquals | |
static void | assertEquals (Object expected, Object actual) Asserts that two objects are equal. | |
static void | assertEquals (String message, double expected, double actual) Deprecated. Use assertEquals(String message, double expected, double actual, double delta) instead | |
static void | assertEquals (String message, double expected, double actual, double delta) Asserts that two doubles are equal to within a positive delta. | |
static void | assertEquals (String message, float expected, float actual, float delta) Asserts that two floats are equal to within a positive delta. | |
static void | assertEquals (String message, long expected, long actual) Asserts that two longs are equal. | |
static void | assertEquals (String message, Object[] expecteds, Object[] actuals) Deprecated. use assertArrayEquals | |
static void | assertEquals (String message, Object expected, Object actual) Asserts that two objects are equal. | |
static void | assertFalse (boolean condition) Asserts that a condition is false. | |
static void | assertFalse (String message, boolean condition) Asserts that a condition is false. | |
static void | assertNotEquals (double unexpected, double actual, double delta) Asserts that two doubles are not equal to within a positive delta. | |
static void | assertNotEquals (float unexpected, float actual, float delta) Asserts that two floats are not equal to within a positive delta. | |
static void | assertNotEquals (long unexpected, long actual) Asserts that two longs are not equals. | |
static void | assertNotEquals (Object unexpected, Object actual) Asserts that two objects are not equals. | |
static void | assertNotEquals (String message, double unexpected, double actual, double delta) Asserts that two doubles are not equal to within a positive delta. | |
static void | assertNotEquals (String message, float unexpected, float actual, float delta) Asserts that two floats are not equal to within a positive delta. | |
static void | assertNotEquals (String message, long unexpected, long actual) Asserts that two longs are not equals. | |
static void | assertNotEquals (String message, Object unexpected, Object actual) Asserts that two objects are not equals. | |
static void | assertNotNull (Object object) Asserts that an object isn’t null. | |
static void | assertNotNull (String message, Object object) Asserts that an object isn’t null. | |
static void | assertNotSame (Object unexpected, Object actual) Asserts that two objects do not refer to the same object. | |
static void | assertNotSame (String message, Object unexpected, Object actual) Asserts that two objects do not refer to the same object. | |
static void | assertNull (Object object) Asserts that an object is null. | |
static void | assertNull (String message, Object object) Asserts that an object is null. | |
static void | assertSame (Object expected, Object actual) Asserts that two objects refer to the same object. | |
static void | assertSame (String message, Object expected, Object actual) Asserts that two objects refer to the same object. | |
static
| assertThat (String reason, T actual, Matcher matcher) Deprecated. use org.hamcrest.MatcherAssert.assertThat() | |
static
| assertThat (T actual, Matcher matcher) Deprecated. use org.hamcrest.MatcherAssert.assertThat() | |
static
| assertThrows (Class expectedThrowable, ThrowingRunnable runnable) Asserts that runnable throws an exception of type expectedThrowable when executed. | |
static
| assertThrows (String message, Class expectedThrowable, ThrowingRunnable runnable) Asserts that runnable throws an exception of type expectedThrowable when executed. | |
static void | assertTrue (boolean condition) Asserts that a condition is true. | |
static void | assertTrue (String message, boolean condition) Asserts that a condition is true. | |
static void | fail () Fails a test with no message. | |
static void | fail (String message) Fails a test with the given message. |
Methods inherited from class java.lang.Object |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Constructor Detail |
---|
Assert
Method Detail |
---|
assertTrue
Parameters: message — the identifying message for the AssertionError ( null okay) condition — condition to be checked
assertTrue
Parameters: condition — condition to be checked
assertFalse
Parameters: message — the identifying message for the AssertionError ( null okay) condition — condition to be checked
assertFalse
Parameters: condition — condition to be checked
Parameters: message — the identifying message for the AssertionError ( null okay) See Also: AssertionError
assertEquals
Parameters: message — the identifying message for the AssertionError ( null okay) expected — expected value actual — actual value
assertEquals
Parameters: expected — expected value actual — the value to check against expected
assertNotEquals
Parameters: message — the identifying message for the AssertionError ( null okay) unexpected — unexpected value to check actual — the value to check against unexpected
assertNotEquals
Parameters: unexpected — unexpected value to check actual — the value to check against unexpected
assertNotEquals
Parameters: message — the identifying message for the AssertionError ( null okay) unexpected — unexpected value to check actual — the value to check against unexpected
assertNotEquals
Parameters: unexpected — unexpected value to check actual — the value to check against unexpected
assertNotEquals
Parameters: message — the identifying message for the AssertionError ( null okay) unexpected — unexpected value actual — the value to check against unexpected delta — the maximum delta between unexpected and actual for which both numbers are still considered equal.
assertNotEquals
Parameters: unexpected — unexpected value actual — the value to check against unexpected delta — the maximum delta between unexpected and actual for which both numbers are still considered equal.
assertNotEquals
Parameters: unexpected — unexpected value actual — the value to check against unexpected delta — the maximum delta between unexpected and actual for which both numbers are still considered equal.
assertArrayEquals
Parameters: message — the identifying message for the AssertionError ( null okay) expecteds — Object array or array of arrays (multi-dimensional array) with expected values. actuals — Object array or array of arrays (multi-dimensional array) with actual values Throws: org.junit.internal.ArrayComparisonFailure
assertArrayEquals
Parameters: expecteds — Object array or array of arrays (multi-dimensional array) with expected values actuals — Object array or array of arrays (multi-dimensional array) with actual values
assertArrayEquals
Parameters: message — the identifying message for the AssertionError ( null okay) expecteds — boolean array with expected values. actuals — boolean array with expected values. Throws: org.junit.internal.ArrayComparisonFailure
assertArrayEquals
Parameters: expecteds — boolean array with expected values. actuals — boolean array with expected values.
assertArrayEquals
Parameters: message — the identifying message for the AssertionError ( null okay) expecteds — byte array with expected values. actuals — byte array with actual values Throws: org.junit.internal.ArrayComparisonFailure
assertArrayEquals
Parameters: expecteds — byte array with expected values. actuals — byte array with actual values
assertArrayEquals
Parameters: message — the identifying message for the AssertionError ( null okay) expecteds — char array with expected values. actuals — char array with actual values Throws: org.junit.internal.ArrayComparisonFailure
assertArrayEquals
Parameters: expecteds — char array with expected values. actuals — char array with actual values
assertArrayEquals
Parameters: message — the identifying message for the AssertionError ( null okay) expecteds — short array with expected values. actuals — short array with actual values Throws: org.junit.internal.ArrayComparisonFailure
assertArrayEquals
Parameters: expecteds — short array with expected values. actuals — short array with actual values
assertArrayEquals
Parameters: message — the identifying message for the AssertionError ( null okay) expecteds — int array with expected values. actuals — int array with actual values Throws: org.junit.internal.ArrayComparisonFailure
assertArrayEquals
Parameters: expecteds — int array with expected values. actuals — int array with actual values
assertArrayEquals
Parameters: message — the identifying message for the AssertionError ( null okay) expecteds — long array with expected values. actuals — long array with actual values Throws: org.junit.internal.ArrayComparisonFailure
assertArrayEquals
Parameters: expecteds — long array with expected values. actuals — long array with actual values
assertArrayEquals
Parameters: message — the identifying message for the AssertionError ( null okay) expecteds — double array with expected values. actuals — double array with actual values delta — the maximum delta between expecteds[i] and actuals[i] for which both numbers are still considered equal. Throws: org.junit.internal.ArrayComparisonFailure
assertArrayEquals
Parameters: expecteds — double array with expected values. actuals — double array with actual values delta — the maximum delta between expecteds[i] and actuals[i] for which both numbers are still considered equal.
assertArrayEquals
Parameters: message — the identifying message for the AssertionError ( null okay) expecteds — float array with expected values. actuals — float array with actual values delta — the maximum delta between expecteds[i] and actuals[i] for which both numbers are still considered equal. Throws: org.junit.internal.ArrayComparisonFailure
assertArrayEquals
Parameters: expecteds — float array with expected values. actuals — float array with actual values delta — the maximum delta between expecteds[i] and actuals[i] for which both numbers are still considered equal.
assertEquals
Parameters: message — the identifying message for the AssertionError ( null okay) expected — expected value actual — the value to check against expected delta — the maximum delta between expected and actual for which both numbers are still considered equal.
assertEquals
Parameters: message — the identifying message for the AssertionError ( null okay) expected — expected value actual — the value to check against expected delta — the maximum delta between expected and actual for which both numbers are still considered equal.
assertNotEquals
Parameters: message — the identifying message for the AssertionError ( null okay) unexpected — unexpected value actual — the value to check against unexpected delta — the maximum delta between unexpected and actual for which both numbers are still considered equal.
assertEquals
Parameters: expected — expected long value. actual — actual long value
assertEquals
Parameters: message — the identifying message for the AssertionError ( null okay) expected — long expected value. actual — long actual value
assertEquals
assertEquals
assertEquals
Parameters: expected — expected value actual — the value to check against expected delta — the maximum delta between expected and actual for which both numbers are still considered equal.
assertEquals
Parameters: expected — expected value actual — the value to check against expected delta — the maximum delta between expected and actual for which both numbers are still considered equal.
assertNotNull
Parameters: message — the identifying message for the AssertionError ( null okay) object — Object to check or null
assertNotNull
Parameters: object — Object to check or null
assertNull
Parameters: message — the identifying message for the AssertionError ( null okay) object — Object to check or null
assertNull
Parameters: object — Object to check or null
assertSame
Parameters: message — the identifying message for the AssertionError ( null okay) expected — the expected object actual — the object to compare to expected
assertSame
Parameters: expected — the expected object actual — the object to compare to expected
assertNotSame
Parameters: message — the identifying message for the AssertionError ( null okay) unexpected — the object you don’t expect actual — the object to compare to unexpected
assertNotSame
Parameters: unexpected — the object you don’t expect actual — the object to compare to unexpected
assertEquals
Asserts that two object arrays are equal. If they are not, an AssertionError is thrown with the given message. If expecteds and actuals are null , they are considered equal.
Parameters: message — the identifying message for the AssertionError ( null okay) expecteds — Object array or array of arrays (multi-dimensional array) with expected values. actuals — Object array or array of arrays (multi-dimensional array) with actual values
assertEquals
Asserts that two object arrays are equal. If they are not, an AssertionError is thrown. If expected and actual are null , they are considered equal.
Parameters: expecteds — Object array or array of arrays (multi-dimensional array) with expected values actuals — Object array or array of arrays (multi-dimensional array) with actual values
assertThat
Asserts that actual satisfies the condition specified by matcher . If not, an AssertionError is thrown with information about the matcher and failing value. Example: org.hamcrest.Matcher does not currently document the meaning of its type parameter T . This method assumes that a matcher typed as Matcher can be meaningfully applied only to values that could be assigned to a variable of type T .
Type Parameters: T — the static type accepted by the matcher (this can flag obvious compile-time problems such as assertThat(1, is(«a»)) Parameters: actual — the computed value being compared matcher — an expression, built of Matcher s, specifying allowed values See Also: CoreMatchers
assertThat
Asserts that actual satisfies the condition specified by matcher . If not, an AssertionError is thrown with the reason and information about the matcher and failing value. Example: org.hamcrest.Matcher does not currently document the meaning of its type parameter T . This method assumes that a matcher typed as Matcher can be meaningfully applied only to values that could be assigned to a variable of type T .
Type Parameters: T — the static type accepted by the matcher (this can flag obvious compile-time problems such as assertThat(1, is(«a»)) Parameters: reason — additional information about the error actual — the computed value being compared matcher — an expression, built of Matcher s, specifying allowed values See Also: CoreMatchers
assertThrows
Parameters: expectedThrowable — the expected type of the exception runnable — a function that is expected to throw an exception when executed Returns: the exception thrown by runnable Since: 4.13