Java Unit Testing: JUnit Assert, Mockito Mocks, verify, and Stream peek
This article demonstrates how to use JUnit's Assert methods for various checks, creates mock objects and verifies interactions with Mockito, and leverages Java 8 Stream's peek operation for debugging, providing complete code examples for each technique.
Scenario
When using Java 8 Stream APIs you often need unit tests for the stream operations. This guide shows how to write JUnit assertions, create Mockito mocks, verify mock interactions, and debug streams with the peek method.
JUnit Assert methods
Common assertion methods include: assertEquals(Object expected, Object actual) – checks equality. assertFalse(boolean condition) – expects false. assertTrue(boolean condition) – expects true. assertNotNull(Object obj) – ensures the object is not null. assertNull(Object obj) – ensures the object is null. assertSame(Object expected, Object actual) – checks reference equality. assertNotSame(Object unexpected, Object actual) – checks reference inequality. assertEquals(double expected, double actual, double delta) – checks double values within a tolerance.
Example tests:
@Test
public void testAssertSame() {
String expected = "badao";
String actual = "badao";
assertSame(expected, actual);
}
@Test
public void testAssertNotSame() {
String expected = "badao";
String actual = "badao";
assertNotSame(expected, actual);
}
@Test
public void testAssertEquals() {
int expected = 123;
int actual = 123;
assertEquals(expected, actual);
}
@Test
public void testAssertNotEquals() {
int expected = 123;
int actual = 123;
assertNotEquals(expected, actual);
}
@Test
public void testAssertNull() {
Object obj = null;
assertNull(obj);
}
@Test
public void testAssertNotNull() {
Object obj = null;
assertNotNull(obj);
}
@Test
public void testAssertTrue() {
assertTrue(1 > 2);
}
@Test
public void testAssertFalse() {
assertFalse(1 > 2);
}Mockito mocking
Mockito provides a concise API for creating mock objects and verifying their behavior, avoiding the need for explicit expectations.
Mock examples:
@Test
public void testMockRandom() {
Random mockRandom = mock(Random.class);
// When nextInt() is called, always return 100
when(mockRandom.nextInt()).thenReturn(100);
Assert.assertEquals(100, mockRandom.nextInt());
}
@Test
public void testMockArrayList() {
ArrayList mockArrayList = mock(ArrayList.class);
Assert.assertTrue(mockArrayList instanceof List);
when(mockArrayList.add(1)).thenReturn(true);
Assert.assertTrue(mockArrayList.add(1));
}
@Test
public void testMockIterator() {
Iterator iterator = mock(Iterator.class);
when(iterator.next()).thenReturn("Hello");
// Simulate exception on next()
doThrow(new NullPointerException()).when(iterator).next();
iterator.next();
}Verification with verify:
@Test
public void testVerify() {
List mockedList = mock(List.class);
mockedList.add("aa");
// Verify the method was called at least once
verify(mockedList, atLeastOnce()).add("aa");
// Verify it was never called with "bbb"
verify(mockedList, never()).add("bbb");
}Java 8 Stream peek for debugging
The peek operation lets you observe each element in a stream without terminating the pipeline.
Simple example:
@Test
public void testPeekSimple() {
Stream.of("1", "2", "3")
.peek(s -> System.out.println(s));
}Object list example:
@Test
public void testPeekObjects() {
Album album1 = Album.builder()
.albumName("album1")
.trackList(new ArrayList<Track>(){{
this.add(Track.builder().trackName("a").length(60f).build());
this.add(Track.builder().trackName("b").length(70f).build());
this.add(Track.builder().trackName("c").length(80f).build());
this.add(Track.builder().trackName("d").length(90f).build());
}})
.build();
album1.getTrackList().stream()
.peek(album -> album.setTrackName("badao"))
.forEach(System.out::println);
}Real‑world usage with logging:
@Test
public void testPeekWithLogging() {
Album album1 = Album.builder()
.albumName("album1")
.trackList(new ArrayList<Track>(){{
this.add(Track.builder().trackName("a").length(60f).build());
this.add(Track.builder().trackName("b").length(70f).build());
this.add(Track.builder().trackName("c").length(80f).build());
this.add(Track.builder().trackName("d").length(90f).build());
}})
.build();
album1.getTrackList()
.stream()
.peek(album -> {
System.out.println(album.getTrackName() + "--" + album.getLength());
})
.map(a -> a.getTrackName())
.collect(Collectors.toList())
.forEach(System.out::println);
}Aggregated demo class
package com.ruoyi.demo.java8demo;
import com.ruoyi.demo.domain.Album;
import com.ruoyi.demo.domain.Track;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class unitTestDemo {
// JUnit Assert methods listed as comments
// void assertEquals(Object expected, Object actual) – checks equality
// void assertFalse(boolean condition) – expects false
// void assertTrue(boolean condition) – expects true
// void assertNotNull(Object obj) – expects non‑null
// void assertNull(Object obj) – expects null
// void assertSame(Object expected, Object actual) – reference equality
// void assertNotSame(Object unexpected, Object actual) – reference inequality
// void assertEquals(double expected, double actual, double delta) – double tolerance
@Test
public void test2(){
String expected = "badao";
String actual = "badao";
assertSame(expected, actual);
}
@Test
public void test3(){
String expected = "badao";
String actual = "badao";
assertNotSame(expected, actual);
}
@Test
public void test4(){
int expected = 123;
int actual = 123;
assertEquals(expected, actual);
}
@Test
public void test5(){
int expected = 123;
int actual = 123;
assertNotEquals(expected, actual);
}
@Test
public void test6(){
Object object = null;
assertNull(object);
}
@Test
public void test7(){
Object object = null;
assertNotNull(object);
}
@Test
public void test8(){
assertTrue(1 > 2);
}
@Test
public void test9(){
assertFalse(1 > 2);
}
@Test
public void test1(){
Random mockRandom = mock(Random.class);
// When nextInt() is called, always return 100
when(mockRandom.nextInt()).thenReturn(100);
Assert.assertEquals(100, mockRandom.nextInt());
}
@Test
public void test10(){
ArrayList mockArrayList = mock(ArrayList.class);
Assert.assertTrue(mockArrayList instanceof List);
when(mockArrayList.add(1)).thenReturn(true);
Assert.assertTrue(mockArrayList.add(1));
}
@Test
public void test11(){
Iterator iterator = mock(Iterator.class);
when(iterator.next()).thenReturn("Hello");
// Simulate exception on next()
doThrow(new NullPointerException()).when(iterator).next();
iterator.next();
}
@Test
public void test12(){
List mockedList = mock(List.class);
mockedList.add("aa");
// Verify the method was called at least once
verify(mockedList, atLeastOnce()).add("aa");
// Verify it was called exactly twice (will fail if only once)
verify(mockedList, times(2)).add("aa");
// Verify it was never called with "bbb"
verify(mockedList, never()).add("bbb");
// Verify it was never called with "aaa"
verify(mockedList, never()).add("aaa");
}
@Test
public void test13() {
Stream.of("1", "2", "3")
.peek(s -> System.out.println(s));
}
@Test
public void test14() {
Album album1 = Album.builder()
.albumName("album1")
.trackList(new ArrayList<Track>(){{
this.add(Track.builder().trackName("a").length(60f).build());
this.add(Track.builder().trackName("b").length(70f).build());
this.add(Track.builder().trackName("c").length(80f).build());
this.add(Track.builder().trackName("d").length(90f).build());
}})
.build();
album1.getTrackList().stream()
.peek(album -> album.setTrackName("badao"))
.forEach(System.out::println);
}
@Test
public void test15() {
Album album1 = Album.builder()
.albumName("album1")
.trackList(new ArrayList<Track>(){{
this.add(Track.builder().trackName("a").length(60f).build());
this.add(Track.builder().trackName("b").length(70f).build());
this.add(Track.builder().trackName("c").length(80f).build());
this.add(Track.builder().trackName("d").length(90f).build());
}})
.build();
album1.getTrackList()
.stream()
.peek(album -> {
System.out.println(album.getTrackName() + "--" + album.getLength());
})
.map(a -> a.getTrackName())
.collect(Collectors.toList())
.forEach(System.out::println);
}
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
The Dominant Programmer
Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
