2011-10-13 3 views
0

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 객체에 대한 참조를 가져 오는 방법이 있습니까? 현재 (메인) 스레드에서 비동기 코드를 실행하거나 생성 된 스레드를 조인하고 표명을 수행하려고합니다.

답변

1

처음에는 코드에 오타가 있었으며 IDE에서 다시 시도해도 제대로 작동하지 않았습니다. 이 코드는 Task 초기화에 대해 VerifyError을 던졌습니다. Taskpublic 도움.

모든 것이 올바르게 되었으면 코드가 예상대로 작동하여 실행 파일이 캡처되었음을 의미합니다.

내가 대신 스터 빙 구문 갈 것이지만 :

whenNew(Thread.class).withParameterTypes(Runnable.class) 
    .withArguments(runnables.capture()).thenReturn(mock); 

당신은 올바르게 스텁있어 있는지 확인하기 위해 실제 코드를 조사해야합니다.

관련 문제