javaandroidrobotium

Robotium - customize PAUSE duration in Sleeper class


waitForCondition() on the Solo class in Robotium uses a Sleeper object to sleep a thread in between checking for a condition. The Sleeper class has a PAUSE defined as 500 milliseconds. I want to lower that, ideally without downloading the Robotium source code, changing it, and recompiling Robotium.

I tried extending the Solo class and constructing my own Waiter class that would use a custom Sleeper object with lower sleep intervals, but Waiter has package-level access so this route is not available.

The final keyword aside, this commit message seems to indicate that custom configurations should be (or are coming) but I don't see any way to customize those constants in the Solo.Config class.

Does anyone have any solutions? Thanks!

Update: @vRallev's answer below gets the job done with reflection. I made a pull request that was merged into Robotium today. In the next release, you'll be able to configure sleep times with the Config class.


Solution

  • Even if the Waiter or Sleeper class were public, you couldn't change the values. The reason is that the waiter field in the Solo class is final and the constructor where the value is assigned is private.

    The only way to hack this is with reflection. I tried the solution below and it works. Notice the package of both classes!

    package com.robotium.solo;
    
    import java.lang.reflect.Field;
    
    public class SoloHack {
    
      private final Solo mSolo;
    
      public SoloHack(Solo solo) {
        mSolo = solo;
      }
    
      public void hack() throws NoSuchFieldException, IllegalAccessException {
        Field field = mSolo.waiter.getClass().getDeclaredField("sleeper");
        field.setAccessible(true);
    
        // Object value = field.get(mSolo.waiter);
        // Class<?> aClass = value.getClass();
    
        field.set(mSolo.waiter, new SleeperHack());
    
        // Object newValue = field.get(mSolo.waiter);
        // Class<?> newClass = newValue.getClass();
      }
    }
    

    And

    package com.robotium.solo;
    
    public class SleeperHack extends Sleeper {
    
      @Override
      public void sleep() {
        sleep(50);
      }
    }