Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ import org.mockito.kotlin.whenever
class MongoCursorTest {
@Test
fun shouldHaveTheSameMethods() {
val jMongoCursorFunctions = JMongoCursor::class.declaredFunctions.map { it.name }.toSet()
val jMongoCursorFunctions =
JMongoCursor::class.declaredFunctions.map { it.name }
// exclude since this method has a default implementation in MongoCursor interface
.filterNot { it == "forEachRemaining" }
.toSet()
val kMongoCursorFunctions =
MongoCursorImpl::class.declaredFunctions.map { it.name }.toSet() +
MongoCursorImpl::class
Expand Down
10 changes: 10 additions & 0 deletions driver-sync/src/main/com/mongodb/client/MongoCursor.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import java.io.Closeable;
import java.util.Iterator;
import java.util.function.Consumer;

/**
* The Mongo Cursor interface implementing the iterator protocol.
Expand Down Expand Up @@ -96,4 +97,13 @@ public interface MongoCursor<TResult> extends Iterator<TResult>, Closeable {
* @return ServerAddress
*/
ServerAddress getServerAddress();

@Override
default void forEachRemaining(final Consumer<? super TResult> action) {
try {
Iterator.super.forEachRemaining(action);
} finally {
close();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -184,4 +184,23 @@ class MongoBatchCursorAdapterSpecification extends Specification {
then:
cursor.available() == 0
}

def 'should close cursor in forEachRemaining if there is an exception'() {
given:
def firstBatch = [new Document('x', 1)]

def batchCursor = Mock(BatchCursor)
batchCursor.hasNext() >>> [true, true]
batchCursor.next() >>> [firstBatch]
def cursor = new MongoBatchCursorAdapter(batchCursor)

when:
cursor.forEachRemaining {
throw new IllegalStateException('test')
}

then:
thrown(IllegalStateException)
1 * batchCursor.close()
}
}