Penegasan dalam JUnit 4 dan JUnit 5

1. Pengenalan

Dalam artikel ini, kita akan meneroka secara terperinci pernyataan yang terdapat dalam JUnit.

Setelah berpindah dari artikel JUnit 4 ke JUnit 5 dan Panduan untuk JUnit 5, kita sekarang akan memperincikan pernyataan yang berbeza yang terdapat dalam JUnit 4 dan JUnit 5.

Kami juga akan mengetengahkan peningkatan yang dibuat berdasarkan pernyataan dengan JUnit 5.

2. Ketegasan

Tegasan adalah kaedah utiliti untuk menyokong penegasan syarat dalam ujian ; kaedah ini boleh diakses melalui kelas Assert , di JUnit 4, dan Assertions satu, di JUnit 5.

Untuk meningkatkan pembacaan ujian dan penegasan itu sendiri, selalu disarankan untuk mengimport kelas masing-masing secara statistik. Dengan cara ini, kita dapat merujuk secara langsung kepada kaedah penegasan itu sendiri tanpa kelas mewakili sebagai awalan.

Mari mulakan penerokaan penegasan yang ada dengan JUnit 4.

3. Penegasan dalam JUnit 4

Dalam versi perpustakaan ini, pernyataan tersedia untuk semua jenis primitif, Objek, dan tatasusunan (baik primitif atau Objek).

Susunan parameter, dalam penegasan, adalah nilai yang diharapkan diikuti oleh nilai sebenarnya; secara pilihan parameter pertama boleh menjadi mesej String yang mewakili output mesej dari keadaan yang dinilai.

Hanya ada satu yang sedikit berbeza dalam cara penentuan penegasan itu, tetapi kita akan membahasnya kemudian hari.

Mari mulakan dengan assertEquals .

3.1. menegaskanEquals

The assertEquals Verifies Dakwaan bahawa yang diharapkan dan nilai sebenar adalah sama:

@Test public void whenAssertingEquality_thenEqual() { String expected = "Baeldung"; String actual = "Baeldung"; assertEquals(expected, actual); }

Juga mungkin untuk menentukan mesej yang akan dipaparkan ketika penegasan gagal:

assertEquals("failure - strings are not equal", expected, actual);

3.2. assertArrayEquals

Sekiranya kita ingin menegaskan bahawa dua tatasusunan sama, kita boleh menggunakan assertArrayEquals:

@Test public void whenAssertingArraysEquality_thenEqual() { char[] expected = {'J','u','n','i','t'}; char[] actual = "Junit".toCharArray(); assertArrayEquals(expected, actual); }

Sekiranya kedua-dua tatasusila itu kosong , penegasan akan menganggapnya sama:

@Test public void givenNullArrays_whenAssertingArraysEquality_thenEqual() { int[] expected = null; int[] actual = null; assertArrayEquals(expected, actual); }

3.3. assertNotNull dan assertNull

Apabila kita ingin menguji apakah objek itu nol, kita boleh menggunakan penegasan assertNull :

@Test public void whenAssertingNull_thenTrue() { Object car = null; assertNull("The car should be null", car); }

Dengan cara yang sebaliknya, jika kita ingin menegaskan bahawa objek tidak boleh kosong, kita boleh menggunakan penegasan assertNotNull.

3.4. assertNotSame dan assertSame

Dengan assertNotSame , mungkin untuk mengesahkan jika dua pemboleh ubah tidak merujuk pada objek yang sama:

@Test public void whenAssertingNotSameObject_thenDifferent() { Object cat = new Object(); Object dog = new Object(); assertNotSame(cat, dog); }

Jika tidak, apabila kita ingin mengesahkan bahawa dua pemboleh ubah merujuk pada objek yang sama, kita boleh menggunakan penegasan assertSame .

3.5. assertTrue dan assertFalse

Sekiranya kita ingin mengesahkan bahawa keadaan tertentu benar atau salah , kita masing-masing boleh menggunakan penegasan assertTrue atau assertFalse :

@Test public void whenAssertingConditions_thenVerified() { assertTrue("5 is greater then 4", 5 > 4); assertFalse("5 is not greater then 6", 5 > 6); }

3.6. gagal

Yang gagal dakwaan gagal ujian membuang yang AssertionFailedError . Ini dapat digunakan untuk mengesahkan bahawa pengecualian sebenarnya dilemparkan atau ketika kita ingin membuat ujian gagal semasa pengembangannya.

Mari lihat bagaimana kita dapat menggunakannya dalam senario pertama:

@Test public void whenCheckingExceptionMessage_thenEqual() { try { methodThatShouldThrowException(); fail("Exception not thrown"); } catch (UnsupportedOperationException e) { assertEquals("Operation Not Supported", e.getMessage()); } }

3.7. menegaskan bahawa

The assertThat penegasan adalah satu-satunya di JUnit 4 yang mempunyai susunan terbalik parameter berbanding dakwaan lain.

Dalam kes ini, penegasan mempunyai mesej kegagalan pilihan, nilai sebenarnya, dan objek Matcher .

Mari lihat bagaimana kita dapat menggunakan penegasan ini untuk memeriksa sama ada array mengandungi nilai tertentu:

@Test public void testAssertThatHasItems() { assertThat( Arrays.asList("Java", "Kotlin", "Scala"), hasItems("Java", "Kotlin")); } 

Maklumat tambahan, penggunaan yang kuat daripada assertThat penegasan dengan Matcher objek, boleh didapati di Testing dengan Hamcrest.

4. Teguran JUnit 5

JUnit 5 menyimpan banyak kaedah penegasan JUnit 4 sambil menambahkan beberapa kaedah baru yang memanfaatkan sokongan Java 8.

Juga dalam versi perpustakaan ini, pernyataan tersedia untuk semua jenis primitif, Objek, dan tatasusunan (baik primitif atau Objek).

The order of the parameters of the assertions changed, moving the output message parameter as the last parameter. Thanks to the support of Java 8, the output message can be a Supplier, allowing lazy evaluation of it.

Let's start reviewing the assertions available also in JUnit 4.

4.1. assertArrayEquals

The assertArrayEquals assertion verifies that the expected and the actual arrays are equals:

@Test public void whenAssertingArraysEquality_thenEqual() { char[] expected = { 'J', 'u', 'p', 'i', 't', 'e', 'r' }; char[] actual = "Jupiter".toCharArray(); assertArrayEquals(expected, actual, "Arrays should be equal"); }

If the arrays aren't equal, the message “Arrays should be equal” will be displayed as output.

4.2. assertEquals

In case we want to assert that two floats are equals, we can use the simple assertEquals assertion:

@Test public void whenAssertingEquality_thenEqual() { float square = 2 * 2; float rectangle = 2 * 2; assertEquals(square, rectangle); }

However, if we want to assert that the actual value differs by a predefined delta from the expected value, we can still use the assertEquals but we have to pass the delta value as the third parameter:

@Test public void whenAssertingEqualityWithDelta_thenEqual() { float square = 2 * 2; float rectangle = 3 * 2; float delta = 2; assertEquals(square, rectangle, delta); }

4.3. assertTrue and assertFalse

With the assertTrue assertion, it's possible to verify the supplied conditions are true:

@Test public void whenAssertingConditions_thenVerified() { assertTrue(5 > 4, "5 is greater the 4"); assertTrue(null == null, "null is equal to null"); }

Thanks to the support of the lambda expression, it's possible to supply a BooleanSupplier to the assertion instead of a boolean condition.

Let's see how we can assert the correctness of a BooleanSupplier using the assertFalse assertion:

@Test public void givenBooleanSupplier_whenAssertingCondition_thenVerified() { BooleanSupplier condition = () -> 5 > 6; assertFalse(condition, "5 is not greater then 6"); }

4.4. assertNull and assertNotNull

When we want to assert that an object is not null we can use the assertNotNull assertion:

@Test public void whenAssertingNotNull_thenTrue() { Object dog = new Object(); assertNotNull(dog, () -> "The dog should not be null"); }

In the opposite way, we can use the assertNull assertion to check if the actual is null:

@Test public void whenAssertingNull_thenTrue() { Object cat = null; assertNull(cat, () -> "The cat should be null"); }

In both cases, the failure message will be retrieved in a lazy way since it's a Supplier.

4.5. assertSame and assertNotSame

When we want to assert that the expected and the actual refer to the same Object, we must use the assertSame assertion:

@Test public void whenAssertingSameObject_thenSuccessfull() { String language = "Java"; Optional optional = Optional.of(language); assertSame(language, optional.get()); }

In the opposite way, we can use the assertNotSame one.

4.6. fail

The fail assertion fails a test with the provided failure message as well as the underlying cause. This can be useful to mark a test when it's development it's not completed:

@Test public void whenFailingATest_thenFailed() { // Test not completed fail("FAIL - test not completed"); }

4.7. assertAll

One of the new assertion introduced in JUnit 5 is assertAll.

This assertion allows the creation of grouped assertions, where all the assertions are executed and their failures are reported together. In details, this assertion accepts a heading, that will be included in the message string for the MultipleFailureError, and a Stream of Executable.

Let's define a grouped assertion:

@Test public void givenMultipleAssertion_whenAssertingAll_thenOK() { assertAll( "heading", () -> assertEquals(4, 2 * 2, "4 is 2 times 2"), () -> assertEquals("java", "JAVA".toLowerCase()), () -> assertEquals(null, null, "null is equal to null") ); }

The execution of a grouped assertion is interrupted only when one of the executables throws a blacklisted exception (OutOfMemoryError for example).

4.8. assertIterableEquals

The assertIterableEquals asserts that the expected and the actual iterables are deeply equal.

In order to be equal, both iterable must return equal elements in the same order and it isn't required that the two iterables are of the same type in order to be equal.

With this consideration, let's see how we can assert that two lists of different types (LinkedList and ArrayList for example) are equal:

@Test public void givenTwoLists_whenAssertingIterables_thenEquals() { Iterable al = new ArrayList(asList("Java", "Junit", "Test")); Iterable ll = new LinkedList(asList("Java", "Junit", "Test")); assertIterableEquals(al, ll); }

In the same way of the assertArrayEquals, if both iterables are null, they are considered equal.

4.9. assertLinesMatch

The assertLinesMatch asserts that the expected list of String matches the actual list.

This method differs from the assertEquals and assertIterableEquals since, for each pair of expected and actual lines, it performs this algorithm:

  1. check if the expected line is equal to the actual one. If yes it continues with the next pair
  2. treat the expected line as a regular expression and performs a check with the String.matches() method. If yes it continues with the next pair
  3. check if the expected line is a fast-forward marker. If yes apply fast-forward and repeat the algorithm from the step 1

Let's see how we can use this assertion to assert that two lists of String have matching lines:

@Test public void whenAssertingEqualityListOfStrings_thenEqual() { List expected = asList("Java", "\\d+", "JUnit"); List actual = asList("Java", "11", "JUnit"); assertLinesMatch(expected, actual); }

4.10. assertNotEquals

Complementary to the assertEquals, the assertNotEquals assertion asserts that the expected and the actual values aren't equal:

@Test public void whenAssertingEquality_thenNotEqual() { Integer value = 5; // result of an algorithm assertNotEquals(0, value, "The result cannot be 0"); }

If both are null, the assertion fails.

4.11. assertThrows

In order to increase simplicity and readability, the new assertThrows assertion allows us a clear and a simple way to assert if an executable throws the specified exception type.

Let's see how we can assert a thrown exception:

@Test void whenAssertingException_thenThrown() { Throwable exception = assertThrows( IllegalArgumentException.class, () -> { throw new IllegalArgumentException("Exception message"); } ); assertEquals("Exception message", exception.getMessage()); }

The assertion will fail if no exception is thrown, or if an exception of a different type is thrown.

4.12. assertTimeout and assertTimeoutPreemptively

In case we want to assert that the execution of a supplied Executable ends before a given Timeout, we can use the assertTimeout assertion:

@Test public void whenAssertingTimeout_thenNotExceeded() { assertTimeout( ofSeconds(2), () -> { // code that requires less then 2 minutes to execute Thread.sleep(1000); } ); }

However, with the assertTimeout assertion, the supplied executable will be executed in the same thread of the calling code. Consequently, execution of the supplier won't be preemptively aborted if the timeout is exceeded.

In case we want to be sure that execution of the executable will be aborted once it exceeds the timeout, we can use the assertTimeoutPreemptively assertion.

Kedua-dua kenyataan boleh menerima, bukannya Laku, yang ThrowingSupplier , yang mewakili mana-mana blok generik kod yang pulangan objek dan yang berpotensi boleh membuang dilontar.

5. Kesimpulan

Dalam tutorial ini, kami merangkumi semua penegasan yang terdapat dalam JUnit 4 dan JUnit 5.

Kami menyoroti secara ringkas penambahbaikan yang dibuat di JUnit 5, dengan pengenalan penegasan baru dan sokongan lambda.

Seperti biasa, kod sumber lengkap untuk artikel ini terdapat di GitHub.