Home > Software engineering >  test method is running infinitely until i forcebly stop it
test method is running infinitely until i forcebly stop it

Time:11-10

@Test
void interruptedExceptionThrownByCompletableFutures() throws InterruptedException, ExecutionException {
    //given
    when(patientsClient.getPatientTreatmentDetails(RPT_TOKEN, "123", CLINICAL_ID))
            .thenReturn(createPatientTreatmentDetails());
    CompletableFuture<List<HDTreatmentOrder>> hdFuture = spy(CompletableFuture.completedFuture(Collections.emptyList()));
    when(hdFuture.get()).thenThrow(new InterruptedException());

    CompletableFuture<List<PDTreatmentOrder>> pdFuture = spy(CompletableFuture.completedFuture(Collections.emptyList()));
    when(pdFuture.get()).thenThrow(new InterruptedException());

    when(hdService.getData(any(), any())).thenReturn(hdFuture);
    when(pdService.getData(any(), any())).thenReturn(pdFuture);

    when(tDService.getData(RPT_TOKEN,
            "123", filter)).thenReturn(CompletableFuture.completedFuture(new PatientTreatmentDetails()));
    //then
    assertThrows(PatientOrderException.class, () -> treatmentOrderService.getTreatmentOrders("123", filter, RPT_TOKEN));
}


This is treatMentOrderService public class TreatmentOrderService {

private final HDTreatmentOrderService hdService;
private final PDTreatmentOrderService pdService;
private final TreatmentDetailsService tDService;
private final TreatmentOrderTransform transformer;
private final DenodoLastTreatmentDetailsService denodoLastTreatmentDetailsService;


public TreatmentOrderService(HDTreatmentOrderService hdService,
                             PDTreatmentOrderService pdService,
                             TreatmentDetailsService tDService,
                             TreatmentOrderTransform transformer,
                             DenodoLastTreatmentDetailsService denodoLastTreatmentDetailsService) {
    this.hdService = hdService;
    this.pdService = pdService;
    this.tDService = tDService;
    this.transformer = transformer;
    this.denodoLastTreatmentDetailsService = denodoLastTreatmentDetailsService;
}


public Page<TreatmentOrderDto> getTreatmentOrders(@NonNull String mpi,
                                                  @NonNull TreatmentOrdersFilter filter, String rptToken) {
    if (filter.isCwowPatient()) {
        return denodoLastTreatmentDetailsService.getCwowLastTreatmentDetails(mpi, filter);
    }

    CompletableFuture<List<HDTreatmentOrder>> hdFuture = hdService.getData(mpi, filter);
    CompletableFuture<List<PDTreatmentOrder>> pdFuture = pdService.getData(mpi, filter);
    try {
        if (filter.isIncludeTreatmentDetails() && StringUtils.isNotEmpty(filter.getClinicId())) {
            CompletableFuture<PatientTreatmentDetails> tDFuture = tDService.getData(rptToken, mpi, filter);
            CompletableFuture.allOf(hdFuture, pdFuture, tDFuture).join();
            return transformer.transform(hdFuture.get(), pdFuture.get(), tDFuture.get(), filter);
        } else {
            CompletableFuture.allOf(hdFuture, pdFuture).join();
            return transformer.transform(hdFuture.get(), pdFuture.get(), null, filter);
        }
    } catch (InterruptedException e) {
        log.error("InterruptedException: ", e);
        Thread.currentThread().interrupt();
        throw new PatientOrderException("Failed executing async tasks: "   e.getMessage());
    } catch (ExecutionException e) {
        log.error("ExecutionException: ", e);
        throw new PatientOrderException("Failed executing async tasks: "   e.getMessage());
    }
}

}

Nov 09, 2022 12:44:51 PM org.junit.platform.launcher.core.EngineDiscoveryOrchestrator lambda$logTestDescriptorExclusionReasons$7
INFO: 0 containers and 20 tests were Method or class mismatch


PatientTreatmentDetails cannot be returned by toString()
toString() should return String
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
   Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
PatientTreatmentDetails cannot be returned by toString()
toString() should return String
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
   Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

    at app//com.davita.ehr.orders.patientorder.service.TreatmentOrderServiceTest.setup(TreatmentOrderServiceTest.java:84)
    at [email protected]/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at [email protected]/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at [email protected]/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at [email protected]/java.lang.reflect.Method.invoke(Method.java:568)
    at app//org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
    at app//org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at app//org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at app//org.junit.jupiter.engine.extension.TimeoutExtension.interceptLifecycleMethod(TimeoutExtension.java:126)
    at app//org.junit.jupiter.engine.extension.TimeoutExtension.interceptBeforeEachMethod(TimeoutExtension.java:76)
    at app//org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at app//org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at app//org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at app//org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at app//org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeMethodInExtensionContext(ClassBasedTestDescriptor.java:506)
    at app//org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$synthesizeBeforeEachMethodAdapter$21(ClassBasedTestDescriptor.java:491)
    at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeEachMethods$3(TestMethodTestDescriptor.java:171)
    at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeMethodsOrCallbacksUntilExceptionOccurs$6(TestMethodTestDescriptor.java:199)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeMethodsOrCallbacksUntilExceptionOccurs(TestMethodTestDescriptor.java:199)
    at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeEachMethods(TestMethodTestDescriptor.java:168)
    at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
    at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at app//org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at [email protected]/java.util.ArrayList.forEach(ArrayList.java:1511)
    at app//org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at app//org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at [email protected]/java.util.ArrayList.forEach(ArrayList.java:1511)
    at app//org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at app//org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at app//org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at app//org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at app//org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at [email protected]/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at [email protected]/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at [email protected]/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at [email protected]/java.lang.reflect.Method.invoke(Method.java:568)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at jdk.proxy2/jdk.proxy2.$Proxy5.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker$3.run(TestWorker.java:193)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
    at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
    at app//worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
    at app//worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)


Disconnected from the target VM, address: 'localhost:51661', transport: 'socket'
TreatmentOrderServiceTest > interruptedExceptionThrownByCompletableFutures() FAILED
    org.mockito.exceptions.misusing.WrongTypeOfReturnValue at TreatmentOrderServiceTest.java:84

-> This test is not executing and when i run this individually this is running continuously until i stop. i'm thinking there is some thing wrong with this test especially the completable future with spy.

using java 17 springboot 2.6.6 junit 5 gradle 7.4.2

CodePudding user response:

Try to rewrite this part

CompletableFuture<List<HDTreatmentOrder>> hdFuture = spy(CompletableFuture.completedFuture(Collections.emptyList()));
when(hdFuture.get()).thenThrow(new InterruptedException())

as

doThrow(InterruptedException.class).when(hdFuture).get();

The same for the other spy:

CompletableFuture<List<PDTreatmentOrder>> pdFuture = spy(CompletableFuture.completedFuture(Collections.emptyList()));
when(pdFuture.get()).thenThrow(new InterruptedException());

as

doThrow(InterruptedException.class).when(pdFuture).get();

CodePudding user response:

When spying on the CompletableFutures like that, they don't seem to be considered "completed" by CompletableFuture.join().

I think what you should use instead is:

when(hdService.getData(any(), any())).thenReturn(CompletableFuture.failedFuture(new InterruptedException()));
when(pdService.getData(any(), any())).thenReturn(CompletableFuture.failedFuture(new InterruptedException()));

and you don't need the hdFuture and pdFuture spies.

Your exception handling in TreatmentOrderService may need fixing, but the test completes instead of hanging.

CodePudding user response:

Actually, there is probably no need for the CompletableFuture.join(). Since you're doing the .get()s in the next line, the thread will block at that point until the futures complete one way or another anyway.

Simply removing the CompletableFuture.allOf(...).join() lines (and the modifications recommended by @pzelenovic) result in the test passing (except for unnecessary stubbings...).

  • Related