### Question:
MongoDatabaseHandler extends SimpleChannelInboundHandler<ClientRequest> { CompletionStage<MongoReply> handleQueryAsync(MongoQuery query) { if (query.getCollectionName().startsWith("$cmd")) { return handleCommandAsync(query) .handle((document, ex) -> createResponseMongoReplyForCommand(query, document, ex)); } return mongoBackend.handleQueryAsync(query) .handle((queryResult, ex) -> createResponseMongoReplyForQuery(query, queryResult, ex)); } MongoDatabaseHandler(MongoBackend mongoBackend, ChannelGroup channelGroup); @Override void channelActive(ChannelHandlerContext ctx); @Override void channelInactive(ChannelHandlerContext ctx);  }### Answer:
@Test void testHandleQueryUnknownCollection() throws Exception { final MongoBackend backend = mock(MongoBackend.class); when(backend.handleQueryAsync(any())).thenCallRealMethod(); final Channel channel = mock(Channel.class); final MessageHeader header = new MessageHeader(0, 0); final MongoQuery query = new MongoQuery(channel, header, "dbName.$cmd.unknown", 0, 0, null, null); final MongoDatabaseHandler handler = new MongoDatabaseHandler(backend, null); MongoReply responseMongoReply = handler.handleQueryAsync(query).toCompletableFuture().get(); assertThat(responseMongoReply).isNotNull(); List<Document> documents = responseMongoReply.getDocuments(); assertThat(documents).isNotEmpty(); Document doc = documents.get(0); assertThat(doc).isNotNull(); assertThat(doc.get("$err")).isEqualTo("unknown collection: $cmd.unknown"); assertThat(doc.get("errmsg")).isEqualTo("unknown collection: $cmd.unknown"); assertThat(doc.get("ok")).isEqualTo(0); }
@Test void testHandleQueryUnknownError() throws Exception { final MongoBackend backend = mock(MongoBackend.class); when(backend.handleQueryAsync(any())).thenCallRealMethod(); when(backend.handleQuery(any())).thenThrow(new RuntimeException("unexpected")); final Channel channel = mock(Channel.class); final MessageHeader header = new MessageHeader(0, 0); final MongoQuery query = new MongoQuery(channel, header, "dbName.find", 0, 0, null, null); final MongoDatabaseHandler handler = new MongoDatabaseHandler(backend, null); MongoReply responseMongoReply = handler.handleQueryAsync(query).toCompletableFuture().get(); assertThat(responseMongoReply).isNotNull(); List<Document> documents = responseMongoReply.getDocuments(); assertThat(documents).isNotEmpty(); Document doc = documents.get(0); assertThat(doc).isNotNull(); assertThat(doc.get("$err")).isEqualTo("Unknown error: unexpected"); assertThat(doc.get("errmsg")).isEqualTo("Unknown error: unexpected"); assertThat(doc.get("ok")).isEqualTo(0); }