Статьи

Модульное тестирование с помощью вызовов @Async

Использование асинхронных действий использовалось в клиентских системах уже несколько лет. Этот же подход становится популярным среди основанных на Java фреймворков. Spring предоставляет  @Async аннотацию (org.springframework.scheduling.annotation.Async) в качестве точки входа в такую ​​функциональность.

Несмотря на то, что может быть легко найти примеры для руководства по реализации  @Async функциональности, добавление покрытия модульных тестов может быть не таким простым.

Моя цель в этой статье — предоставить пример @Async функциональности модульного тестирования  .

Отключенный вызов

Работая над проектом, в котором использовался реактивный подход на стороне клиента, мы обнаружили, что необходимо сообщать клиенту «отключенные изменения». То, что я имею в виду под несвязанными изменениями, в основном связано с моделью данных, которую мы не могли изменить.

В качестве примера рассмотрим сценарий, в котором приложение обрабатывает некоторые аспекты публикации. После внесения изменений в публикацию создается предварительный просмотр — подобно тому, как Microsoft Word может сохранять предварительный просмотр документов (который отображается при сканировании документов из файловой системы). В этом случае отключенным вызовом было время окончания предварительного просмотра. Дизайн базы данных, не обеспечивающий прямой связи между страницей и ее обновленным местоположением предварительного просмотра, округлил оставшуюся часть отсоединенного вызова.

Из-за этого странного состояния пользователи не видели обновленных изображений предварительного просмотра, если они не обновили свои браузеры. Это было неприемлемое поведение.

(Подключено) Решение

Earlier in the project redesign, our team decided to utilize server-sent events (SSEs) to communicate changes in the application. Since this is a publication-based application, several users will be working on the same publication at any given time. As a result, changes will be occurring constantly. The expectation is that those changes simply appear before the user and do not require the user to refresh or reload the browser to see the changes.

The SSE implementation in place was monitoring JPA activities and will broadcast them to a message queue. That message queue would ingest the message, determine if the class containing the change could be converted into a DTO, which was expected by the client-based application. If so, the object was converted to a scaled-down DTO and sent as an SSE, which would then be updated in the reactive store within Angular running on each browser-based client session.

In this case, the disconnected updates could be discovered because there is a table in the application to store version information about each render event for the publication previews. The disconnected part is with the scaled-down versions (like thumbnail previews), which do not have a direct link to the publication page that needs a new preview. Again, this was due to a design in the database that could not be changed at this point.

Before sending the valid  Set<EventDto>eventDtos as an SSE, the following logic was added to the code:

processPagePreviewUpdates(documentId, eventDtos);

Which called this simple private method:

private void processPagePreviewUpdates(Long documentId, Set<EventDto> eventDtos) {
    if (indirectUpdateExists(eventDtos, ImageDto.class.getSimpleName()) {
        dtoChangeEventService.processIndirectPageUpdates(documentId, eventDtos);
    }
}

The boolean helper method uses a stream to determine if any of the elements in the  Set<EventDto>eventDtos are an instance of the ImageDto class.

private boolean indirectUpdateExists(Set<EventDto> eventDtos, String simpleClassName) {
    return eventDtos.stream()
            .filter(i -> i.getType().equals(simpleClassName))
            .count() > 0;
}

For those valid ImageDto elements, the processIndirectPageUpdates()  method uses the @Async  attribute, which will accomplish the following tasks:

  • Locate any page that uses the id provided within the ImageDto object

  • If a match is found, create a new EventDto that contains the page which has the new preview

  • Publish the EventDto as an SSE using a DtoChangeEvent class (designed to communicate non-JPA changes)

This is all at a high level to protect the intellectual property of the client.

The Unit Test

Creating the necessary unit test coverage for the @Async  method required implementing a pattern I had not seen before, using the verify()  method from Mockito.

Without getting into the protected code used on the project, the unit tests have the necessary when()  methods to setup mocked returns for services utilized by the system under test:

when(pageRepository.getPageByPreviewImageId(image.getId())).thenReturn(pageVO);
when(conversionService.convert(pageVO))).thenReturn(pageDto);

In the case of this example, the DtoChangeEvent being published has a void method return type. As a result, the doNothing() Mockito method was added to the tests:

doNothing().when(documentEventPublisher).publish(any(DocumentEvent.class), any(JmsHeaderDecorator.class));

Next, the service under test is called and the verify()  methods are introduced afterward, in order to give the @Async  functionality time to respond:

The verify()  method is constructed in a manner that includes the call portion of the mocked event and not the response that will be provided. That portion is already covered in the  when() method.

try {
    dtoChangeEventService.processIndirectPageUpdates(documentId, eventDTOs);

    verify(pageRepository, timeout(100).times(1)).getPageByPreviewImageId(image.getId());
    verify(conversionService, timeout(100).times(1)).convert(pageVO));

    assertTrue(true);
} catch (Exception e) {
    fail();
}

If these processes complete without any exceptions, I call the  assertTrue() method to mark the test as passed. Otherwise, the fail()method is called.

Had the original process returned values, the actual results could be compared against the mocked-up result set that was expected. These, of course, would replace the simple assertTrue(true)  line in the code.

Hope this helps and have a really great day!