Testing Flashcards
Types of testing?
Unit testing - functions/interfaces
System Testing -
Integration Testing
@DisplayName
annotation to change name of the test in the left bottom corner of the IDE
assertEquals
The assertEquals assertion verifies that the expected and the actual values are equal:
assertArrayEquals
If we want to assert that two arrays are equals, we can use the assertArrayEquals:
@Test
public void whenAssertingArraysEquality_thenEqual() {
char[] expected = {‘J’,’u’,’n’,’i’,’t’};
char[] actual = “Junit”.toCharArray();
assertArrayEquals(expected, actual); }
assertNotNull and assertNull
@Test
public void whenAssertingNull_thenTrue() {
Object car = null;
assertNull("The car should be null", car); } In the opposite way, if we want to assert that an object should not be null we can use the assertNotNull assertion.
assertNotSame and assertSame
With assertNotSame, it’s possible to verify if two variables don’t refer to the same object:
@Test public void whenAssertingNotSameObject_thenDifferent() { Object cat = new Object(); Object dog = new Object();
assertNotSame(cat, dog); } Otherwise, when we want to verify that two variables refer to the same object, we can use the assertSame assertion.
assertTrue and assertFalse
In case we want to verify that a certain condition is true or false, we can respectively use the assertTrue assertion or the assertFalse one:
@Test
public void whenAssertingConditions_thenVerified() {
assertTrue(“5 is greater then 4”, 5 > 4);
assertFalse(“5 is not greater then 6”, 5 > 6);
}
fail
The fail assertion fails a test throwing an AssertionFailedError. It can be used to verify that an actual exception is thrown or when we want to make a test failing during its development.
Let’s see how we can use it in the first scenario:
@Test
public void whenCheckingExceptionMessage_thenEqual() {
try {
methodThatShouldThrowException();
fail(“Exception not thrown”);
} catch (UnsupportedOperationException e) {
assertEquals(“Operation Not Supported”, e.getMessage());
}
}
assertThat
The assertThat assertion is the only one in JUnit 4 that has a reverse order of the parameters compared to the other assertions.
In this case, the assertion has an optional failure message, the actual value, and a Matcher object.
Let’s see how we can use this assertion to check if an array contains particular values:
@Test public void testAssertThatHasItems() { assertThat( Arrays.asList("Java", "Kotlin", "Scala"), hasItems("Java", "Kotlin")); }
assertAll
checks for multiple methods in the same time
assertTimeout
Difference between assertion and assumption
Assumption
met- Test runs
not met- Test gets aborted
Assertion
met- Test Succeeds
not met- Test fails
@Nested
Will make the child class test get running when the we run the class test
@Inject
Annotation used for junit 5 for DI
@ExtendsWith
Will put it on top of the class in which we are going to perform our tests on and decorate it with