mardi 14 janvier 2020

Check mobile connection with Runtime Unit testing

I am trying to build an unit test for this method

public static boolean isOnline(){
    final String command = "ping -c 1 google.com";
    boolean isConnected = false;
    try {
        isConnected = Runtime.getRuntime().exec(command).waitFor() == 0;
    } catch (InterruptedException | IOException e) {
        e.printStackTrace();
    }
    return isConnected;
}

but I'm totally stuck with this problem. I tried to this with PowerMockito like that

@RunWith(PowerMockRunner.class)
@PrepareForTest(Utils.class)
public class TestConnection {

   @Mock
   private Runtime mockRuntime;

   @Mock
   private  Process process;

   @Test
   public void test() throws InterruptedException {

       String command = "ping -c 1 google.com";

       boolean isConnected = false;

       PowerMockito.mockStatic(Runtime.class);

       try {
           process = mockRuntime.exec("ping -c 1 google.com");
       } catch (IOException e) {
           e.printStackTrace();
       }
       when(process.waitFor()).thenReturn(0);

       if (process.waitFor() == 0){
           isConnected = true;
       }
       Assert.assertThat(isConnected, CoreMatchers.is(Utils.isOnline()));
       // do the rest of your test
   }
}

it's my first time with mockito and powerMokito and I don't know where I did Wrong

Aucun commentaire:

Enregistrer un commentaire