Выполнение функций лямбда внутри потоков TransactionExecutor для модульных тестовJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Выполнение функций лямбда внутри потоков TransactionExecutor для модульных тестов

Сообщение Anonymous »

У меня мало методов, которые должны быть итерация в новых транзакциях, но сталкиваемся с ошибками, когда я пытаюсь писать для них модульные тесты < /p>

Код: Выделить всё

@Override
public void schedule(SelfReferralAutoCloseConfigurationData configuration)
{
stopwatch = Stopwatch.createStarted();

lastProcessedReferralDateTime = autoClosedSelfReferralInformationHelper.getCreatedDateTime(configuration);
initialStartedTime = lastProcessedReferralDateTime;
long pageTotalCount;
long pageCount;

do
{
final long[] pageTotalCountHolder = new long[1];
final long[] pageCountHolder = new long[1];

transactionExecutor.runInNewReadOnlyTransaction(() -> {
final Page demandForCarePage = loadDemandForCarePage(configuration);
List openRequests = demandForCarePage.getContent();

pageTotalCountHolder[0] = demandForCarePage.getTotal();
pageCountHolder[0] = demandForCarePage.getContent().size();

complete(configuration, openRequests);
});

pageTotalCount = pageTotalCountHolder[0];
pageCount = pageCountHolder[0];
}
while (
schedulerUtil.isWithinExecutionTimeLimit(configuration.getExecutionTime(), stopwatch.elapsed(TimeUnit.HOURS)) &&
pageTotalCount > pageCount);

infoLogs(configuration, pageTotalCount == pageCount);

totalCount = 0;
closedCount = 0;
}

private void complete(SelfReferralAutoCloseConfigurationData configuration, List openRequests)
{
transactionExecutor.runInNewReadOnlyTransaction(() -> {
System.out.println("Processing " + openRequests.size() + " self referrals to complete.");
for (DemandForCare dfc : openRequests)
{
try
{
if (filter.filter(dfc, configuration))
{
handler.autoComplete(dfc.getId(), configuration.getCloseReason(), configuration.getMode());
closedCount++;
LOG.debug("Completed referral Id: {}", dfc.getId());
}
}
catch (Exception e)
{
if (e.getMessage() != null)
{
LOG.debug("Couldn't complete referral Id: {} and throws the error as {}", dfc.getId(), e.getMessage());
}
else
{
LOG.debug("Couldn't complete referral Id: {} and throws the error as ", dfc.getId(), e);
}
}
totalCount++;
lastProcessedReferralDateTime = dfc.getCreationInfo().getCreatedDateTime();
}
});
}

private Page loadDemandForCarePage(SelfReferralAutoCloseConfigurationData configurationData)
{
return demandForCareDAO.findInProgressSelfReferralsCreatedAfter(lastProcessedReferralDateTime,
new PagingParameters(0,
configurationData.getPageSize(),
Collections.emptyList()));
}
< /code>
Эти методы находятся в центре внимания модульных тестов, и мой текущий тест выглядит так, как это < /p>
@BeforeMethod
public void setUp()
{
MockitoAnnotations.initMocks(this);

when(autoClosedSelfReferralInformationHelper.getCreatedDateTime(any())).thenReturn(new DateTime());

//    reset(transactionExecutor);
//    when(transactionExecutor.runInNewReadOnlyTransaction(any(Callable.class)))
//      .thenAnswer(invocation -> {
//        Callable  callable = invocation.getArgument(0);
//        return callable.call();
//      });
}

@Test
public void testAutoComplete_whenReachingExecutionTime_thenCallingToComplete() throws Exception {
when(schedulerUtil.isWithinExecutionTimeLimit(anyInt(), anyLong())).thenReturn(true).thenReturn(false);
final SelfReferralAutoCloseConfigurationData configurationData = mock(SelfReferralAutoCloseConfigurationData.class);
when(configurationData.getExecutionTime()).thenReturn(1);
final Term closeReason = mock(Term.class);
when(configurationData.getCloseReason()).thenReturn(closeReason);
when(closeReason.getValue()).thenReturn("closeReason");
when(configurationData.getMode()).thenReturn(SelfReferralAutoClosureSchedulerMode.CLOSE_PAST_REFERRALS);
when(configurationData.getPageSize()).thenReturn(3);

List demandForCares = List.of(
getDemandForCare(getDFCId("123")),
getDemandForCare(getDFCId("234")),
getDemandForCare(getDFCId("345"))
);
Page demandForCarePage = new PageImpl(demandForCares, 9, 0);

List demandForCares2 = List.of(
getDemandForCare(getDFCId("1231")),
getDemandForCare(getDFCId("2341")),
getDemandForCare(getDFCId("3451"))
);
Page demandForCarePage2 = new PageImpl(demandForCares, 6, 0);

doReturn(Collections.singletonList(closeReason)).when(termDAO).findByValues(any(String[].class));
doReturn(demandForCarePage, demandForCarePage2).when(demandForCareDAO).findInProgressSelfReferralsCreatedAfter(any(DateTime.class), any(PagingParameters.class));
when(filter.filter(any(DemandForCare.class), any(SelfReferralAutoCloseConfigurationData.class))).thenReturn(true);
doNothing().when(handler).autoComplete(any(DemandForCare.Id.class), any(Term.class), any(SelfReferralAutoClosureSchedulerMode.class));

ArgumentCaptor

Подробнее здесь: [url]https://stackoverflow.com/questions/79769338/executing-lambda-functions-inside-transactionexecutor-threads-for-unit-tests[/url]
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»