У меня мало методов, которые должны быть итерация в новых транзакциях, но сталкиваемся с ошибками, когда я пытаюсь писать для них модульные тесты < /p>
@Inject
private SchedulerUtil schedulerUtil;
@Inject
private CompletableSelfReferralFilter filter;
@Inject
private SelfReferralAutoCloseHandler handler;
@Inject
private DemandForCareDAO demandForCareDAO;
@Inject
private AutoClosedSelfReferralInformationHelper autoClosedSelfReferralInformationHelper;
@Inject
private TransactionExecutor transactionExecutor;
private int closedCount = 0;
private int totalCount = 0;
private Stopwatch stopwatch;
private DateTime initialStartedTime;
private DateTime lastProcessedReferralDateTime;
@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>
public class TransactionExecutor {
private static TransactionExecutor instance;
public TransactionExecutor() {
}
public static TransactionExecutor getInstance() {
return instance;
}
@Inject
public void setInstance(TransactionExecutor transactionExecutor) {
instance = transactionExecutor;
}
@Transactional(
propagation = Propagation.REQUIRES_NEW
)
public void runInNewTransaction(ThrowingRunnable runnable) {
ExceptionWrapper.uncheck(runnable);
}
@Transactional(
propagation = Propagation.REQUIRES_NEW
)
public V runInNewTransaction(Callable callable) {
return ExceptionWrapper.uncheck(callable);
}
@Transactional(
readOnly = true,
propagation = Propagation.REQUIRES_NEW
)
public void runInNewReadOnlyTransaction(ThrowingRunnable runnable) {
ExceptionWrapper.uncheck(runnable);
}
@Transactional(
readOnly = true,
propagation = Propagation.REQUIRES_NEW
)
public V runInNewReadOnlyTransaction(Callable callable) {
return ExceptionWrapper.uncheck(callable);
}
@Transactional(
propagation = Propagation.REQUIRED
)
public void runInTransaction(ThrowingRunnable runnable) {
ExceptionWrapper.uncheck(runnable);
}
@Transactional(
propagation = Propagation.REQUIRED
)
public V runInTransaction(Callable callable) {
return ExceptionWrapper.uncheck(callable);
}
}
< /code>
These methods are the focus of unit tests and my current test looks like this
@Mock
private SelfReferralAutoCloseHandler handler;
@Mock
private DemandForCareDAO demandForCareDAO;
@Mock
private CompletableSelfReferralFilter filter;
@Mock
private TermDAO termDAO;
@Mock
private AutoClosedSelfReferralInformationHelper autoClosedSelfReferralInformationHelper;
@Mock
private SchedulerUtil schedulerUtil;
@Mock
private TransactionExecutor transactionExecutor;
@InjectMocks
private SelfReferralAutoCloseScheduler scheduler;
@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
Подробнее здесь: https://stackoverflow.com/questions/797 ... unit-tests
Выполнение функций лямбда внутри потоков TransactionExecutor для модульных тестов ⇐ JAVA
Программисты JAVA общаются здесь
1758303687
Anonymous
У меня мало методов, которые должны быть итерация в новых транзакциях, но сталкиваемся с ошибками, когда я пытаюсь писать для них модульные тесты < /p>
@Inject
private SchedulerUtil schedulerUtil;
@Inject
private CompletableSelfReferralFilter filter;
@Inject
private SelfReferralAutoCloseHandler handler;
@Inject
private DemandForCareDAO demandForCareDAO;
@Inject
private AutoClosedSelfReferralInformationHelper autoClosedSelfReferralInformationHelper;
@Inject
private TransactionExecutor transactionExecutor;
private int closedCount = 0;
private int totalCount = 0;
private Stopwatch stopwatch;
private DateTime initialStartedTime;
private DateTime lastProcessedReferralDateTime;
@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>
public class TransactionExecutor {
private static TransactionExecutor instance;
public TransactionExecutor() {
}
public static TransactionExecutor getInstance() {
return instance;
}
@Inject
public void setInstance(TransactionExecutor transactionExecutor) {
instance = transactionExecutor;
}
@Transactional(
propagation = Propagation.REQUIRES_NEW
)
public void runInNewTransaction(ThrowingRunnable runnable) {
ExceptionWrapper.uncheck(runnable);
}
@Transactional(
propagation = Propagation.REQUIRES_NEW
)
public V runInNewTransaction(Callable callable) {
return ExceptionWrapper.uncheck(callable);
}
@Transactional(
readOnly = true,
propagation = Propagation.REQUIRES_NEW
)
public void runInNewReadOnlyTransaction(ThrowingRunnable runnable) {
ExceptionWrapper.uncheck(runnable);
}
@Transactional(
readOnly = true,
propagation = Propagation.REQUIRES_NEW
)
public V runInNewReadOnlyTransaction(Callable callable) {
return ExceptionWrapper.uncheck(callable);
}
@Transactional(
propagation = Propagation.REQUIRED
)
public void runInTransaction(ThrowingRunnable runnable) {
ExceptionWrapper.uncheck(runnable);
}
@Transactional(
propagation = Propagation.REQUIRED
)
public V runInTransaction(Callable callable) {
return ExceptionWrapper.uncheck(callable);
}
}
< /code>
These methods are the focus of unit tests and my current test looks like this
@Mock
private SelfReferralAutoCloseHandler handler;
@Mock
private DemandForCareDAO demandForCareDAO;
@Mock
private CompletableSelfReferralFilter filter;
@Mock
private TermDAO termDAO;
@Mock
private AutoClosedSelfReferralInformationHelper autoClosedSelfReferralInformationHelper;
@Mock
private SchedulerUtil schedulerUtil;
@Mock
private TransactionExecutor transactionExecutor;
@InjectMocks
private SelfReferralAutoCloseScheduler scheduler;
@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]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия