PowerMock (ito)를 사용하여 Thread 생성자에 전달 된 Runnable 인스턴스에 대한 참조를 얻는 방법은 무엇입니까?
인수로Runnable
의 인스턴스를 받아들이는 생성자를 사용하여
Thread
을 생성하는 블랙 박스 클래스가 있습니다 :
public class Service {
public static Task implements Runnable {
@Override
public void run() {
doSomeHeavyProcessing();
}
}
public void doAsynchronously() {
new Thread(new Task()).start();
}
}
생성자 호출을 가로 채서 Runnable
를 구현하는 Task
전달에 대한 참조를 얻고 싶습니다. 지금까지의 코드는 다음과 같습니다.
@RunWith(PowerMockRunner.class)
@PrepareForTest(Service.class)
public class ServiceTest {
@Test
public void testService() {
ArgumentCaptor<Runnable> 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
}
}
테스트 실행 결과가 출력됩니다.
all runnables: []
생성자가 반환 한 모든 Runnable
객체 또는 Thread
객체에 대한 참조를 가져 오는 방법이 있습니까? 현재 (메인) 스레드에서 비동기 코드를 실행하거나 생성 된 스레드를 조인하고 표명을 수행하려고합니다.