How do I write a JUnit test case to test threads and events

前端 未结 7 860
无人共我
无人共我 2020-12-09 17:07

I have a java code which works in one (main) thread. From the main thread, i spawn a new thread in which I make a server call. After the server call is done, I am doing some

7条回答
  •  温柔的废话
    2020-12-09 17:41

    Here is my solution to test asynchrone method which used thread.start:

    public class MyClass {      
       public void doSomthingAsynchrone() {
          new Thread(() -> {
             doSomthing();
          }).start();
       }
    
       private void doSomthing() {
       }
    }
    
    @RunWith(PowerMockRunner.class)
    @PrepareForTest(MyClass.class)
    public class MyClassTest {
       ArgumentCaptor runnables = ArgumentCaptor.forClass(Runnable.class);
    
       @InjectMocks
       private MyClass myClass;
    
       @Test
       public void shouldDoSomthingAsynchrone() throws Exception {  
    
          // create a mock for Thread.class
          Thread mock = Mockito.mock(Thread.class);
    
          // mock the 'new Thread', return the mock and capture the given runnable
          whenNew(Thread.class).withParameterTypes(Runnable.class)
                .withArguments(runnables.capture()).thenReturn(mock);
    
          myClass.doSomthingAsynchrone();
    
          runnables.getValue().run();
    
          /**
           *  instead of 'runnables.getValue().run();' you can use a real thread.start
           *
           *   MockRepository.remove(Thread.class);
           *   Thread thread = new Thread(runnables.getValue());
           *   thread.start();
           *   thread.join();
           **/
    
          verify(myClass, times(1)).doSomthing();
       }
    }
    

提交回复
热议问题