What is the preferred way to test event producers (Scenario
vs AsseriblePublishedEvents
)?
#385
-
The documentation shows two ways to test Transactional Event Producers. One uses Below are two examples of these two approaches: @Test
void createAsset_validAssetParameters_assetCreatedSuccessfully_usingScenario(Scenario scenario) {
final String id = RandomStringUtils.randomAlphanumeric(8);
final AssetEntity savedEntity = new AssetEntity(id);
when(assetRepository.save(any(AssetEntity.class))).thenReturn(savedEntity);
scenario.stimulate(() -> assetService.createAsset(assetType, assetTitle))
.andWaitForEventOfType(AssetCreatedEvent.class)
.matchingMappedValue(AssetCreatedEvent::getAssetId, id)
.toArriveAndAssert((eventProduced,returnValue) -> assertReturnedDto(id));
verify(assetRepository).save(any(AssetEntity.class));
} @Test
void createAsset_validAssetParameters_assetCreatedSuccessfully(AssertablePublishedEvents publishedEvents) {
final String id = RandomStringUtils.randomAlphanumeric(8);
final AssetEntity savedEntity = new AssetEntity(id);
when(assetRepository.save(any(AssetEntity.class))).thenReturn(savedEntity);
final AssetDTO assetDTO = assetService.createAsset(assetType, assetTitle);
assertNotNull(assetDTO);
assertEquals(id, assetDTO.getId().id());
verify(assetRepository).save(any(AssetEntity.class));
assertTrue(publishedEvents.eventOfTypeWasPublished(AssetCreatedEvent.class));
final PublishedEvents.TypedPublishedEvents<AssetCreatedEvent> matching = publishedEvents.ofType(AssetCreatedEvent.class)
.matching(AssetCreatedEvent::getId, assetDTO.getId());
} From my understanding, these two do the same thing, but I do not know which is the preferred/better approach. Does it matter at all? Happy to get feedback. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
We generally recommend
|
Beta Was this translation helpful? Give feedback.
We generally recommend
Scenario
as it provides a simplified, more guided API on how to set up a test scenario. It also deals with challenges stemming from the potentially asynchronous integration by using Awaitility under the hood. This is especially helpful in case you test cascading, asynchronously handled events.AssertablePublishedEvents
on the other hand, requires a bit more ceremony, predatesScenario
and is used by that under the covers. UsingAPE
might feel more natural to folks familiar with general AssertJ assertions.