Как смоделировать FindPublisher в реактивном драйвере mon go - PullRequest
1 голос
/ 06 апреля 2020

Я пишу приложение, используя mon go библиотеку реактивного драйвера и реактивного потока в Java.

У меня есть следующий код DAO:

@Override
public Flux<ContentVersion> findBySearch(String appKey, ContentVersionSearchRequest request, Pager pager) {
    final var searchResultsPublisher = mongoClient.getDatabase(appKey)
            .getCollection(COLLECTION_CONTENT_VERSION, ContentVersion.class)
            .find(prepareSearchFilter(request))
            .sort(orderBy(ascending(FIELD_VERSION_STATUS_ORDER), descending(FIELD_UPDATE_DATE)))
            .skip(pager.getSkip())
            .limit(pager.getMax());
    return Flux.from(searchResultsPublisher);
}

В тестах junit: Я издеваюсь над MongoClient, MongoDatabase, MongoCollection, но в конце концов MongoCollection возвращает FindPublisher, и я не знаю, как правильно его смоделировать.

Я успешно написал модульный тест с помощью метода подписки следующим образом. Однако мне это не кажется правильным.

@Mock
private MongoClient mongoClient;

@Mock
private MongoDatabase database;

@Mock
private MongoCollection<ContentVersion> collection;

@Mock
private FindPublisher<ContentVersion> findPublisher;

@Mock
private UpdateResult updateResult;

@InjectMocks
private ContentVersionDaoImpl contentVersionDao;

@BeforeEach
void initCommonMocks() {
    when(mongoClient.getDatabase("ddpApp")).thenReturn(database);
    when(database.getCollection(MongoConstants.COLLECTION_CONTENT_VERSION, ContentVersion.class)).thenReturn(collection);
    when(collection.find(any(Bson.class))).thenReturn(findPublisher);
    when(collection.find(any(Document.class))).thenReturn(findPublisher);
    when(findPublisher.limit(anyInt())).thenReturn(findPublisher);
    when(findPublisher.skip(anyInt())).thenReturn(findPublisher);
    when(findPublisher.sort(any())).thenReturn(findPublisher);
}

@Test
void shouldFindBySearch() {
    final var contentVersion1 = new ContentVersion();
    final var contentVersion2 = new ContentVersion();

    final var testPublisher = TestPublisher.<ContentVersion>createCold()
            .emit(contentVersion1, contentVersion2);

    doAnswer(invocation -> {
        testPublisher.subscribe(invocation.getArgument(0, Subscriber.class));
        return null;
    }).when(findPublisher).subscribe(any());

    final var searchFlux = contentVersionDao
            .findBySearch("ddpApp", new ContentVersionSearchRequest(null, null, null), new Pager(1, 10));

    StepVerifier.create(searchFlux)
            .expectNext(contentVersion1)
            .expectNext(contentVersion2)
            .expectComplete()
            .verify();
}

Кто-нибудь знает элегантный способ написания теста junit для проверки выборки нескольких документов из mongodb?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...