JUnit5 & Mockito
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Welcome!
This playground lets you get started quickly with a simple working example using Maven and JUnit5.
Hands-on Exercise
- Write an assertion to compare two String are equal.
- Write an assertion to check null.
- Write an assertion to check equality of two byte array.
Assertions in JUnit5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// {
package com.tu.code.junit5;
import java.io.FileNotFoundException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
//}
class AssertionsInJUnitFiveTest {
@Test
public void test() throws FileNotFoundException {
try {
success(true);
} catch (AssertionError ae) {
// {
success(false);
msg("Oops! 🐞", ae.getMessage());
//}
}
}
// {
private static void success(boolean success) {
if(success)
msg("👍" ," Awesome");
System.out.println(String.format("TECHIO> success %s", success));
}
private static void msg(String channel, String msg) {
System.out.println(String.format("TECHIO> message --channel \"%s\" \"%s\"", channel, msg));
}
//}
}
Enter to Rename, Shift+Enter to Preview
HamCrest API Matchers
- Write a HamCrest Matcher to check Map has key “John”
- Write a HamCrest Matcher to check Map has entry “John , J”
Using HamCrest in JUnit5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// {
package com.tu.code.junit5;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasEntry;
// }
class HamcrestMatchersTest {
}
Enter to Rename, Shift+Enter to Preview
Mockito in JUnit 5
- Write Mockito Based test case for Messenger class
Mockito in JUnit5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// {
package com.tu.code.junit5;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
// }
class MessengerTest {
}
Enter to Rename, Shift+Enter to Preview
1
package com.tu.code.junit5;
Enter to Rename, Shift+Enter to Preview
1
package com.tu.code.junit5;
Enter to Rename, Shift+Enter to Preview
1
package com.tu.code.junit5;
Enter to Rename, Shift+Enter to Preview
1
package com.tu.code.junit5;
Enter to Rename, Shift+Enter to Preview
1
package com.tu.code.junit5;
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content