Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to obtain a reference to a Runnable instance passed to a Thread constructor using PowerMock(ito)?
    text
    copied!<p>There's a black box class which creates a <code>Thread</code> using its constructor accepting an instance of <code>Runnable</code> as the argument:</p> <pre><code>public class Service { public static Task implements Runnable { @Override public void run() { doSomeHeavyProcessing(); } } public void doAsynchronously() { new Thread(new Task()).start(); } } </code></pre> <p>I want to intercept the constructor call and get a reference to the passing <code>Task</code> implementing <code>Runnable</code>. This is the code so far:</p> <pre><code>@RunWith(PowerMockRunner.class) @PrepareForTest(Service.class) public class ServiceTest { @Test public void testService() { ArgumentCaptor&lt;Runnable&gt; runnables = ArgumentCaptor.forClass(Runnable.class); Thread thread = Mockito.mock(Trhead.class); whenNew(Thread.class.getContructor(Runnable.class)). withArguments(runnables.capture)).thenReturn(thread); new Service().doAsynchronously(); System.out.println("all runnables: " + runnables.getAllValues()); for (Runnable r : runnables.getAllValues()) r.run(); // perform some assertions after the code meant to be executed in a new // thread has been executed in the current (main) thread } } </code></pre> <p>Test execution will print out:</p> <pre><code>all runnables: [] </code></pre> <p>Is there a way of grabbing a reference to all <code>Runnable</code> objects or <code>Thread</code> objects returned by the constructor? I want to execute the asynchronous code either in the current (main) thread or join created threads and perform assertions.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload