0

I am trying to unit test that the behavior with a custom DragCallback was set on my AppBarLayout. There is a set method for setting the dragCallback but not a getter method.

AppBarLayout.Behavior behavior = new AppBarLayout.Behavior();
behavior.setDragCallback(new AppBarLayoutCustomCallback());

It there any way to access the dragCallback of appbarlayout.behavior?

SleepingLlama
  • 528
  • 1
  • 4
  • 8

2 Answers2

0

You can use reflection to get the DragCallback field form Behavior of the AppBarLayout. That field is private and getter is not available probably not to distort the behavior.

  private AppBarLayout.Behavior.DragCallback getDragCallback(AppBarLayout appBarLayout){
        CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        CoordinatorLayout.Behavior behavior = layoutParams.getBehavior();
        if(behavior != null){
            try {
                Field mDragCallbackField = behavior.getClass().getDeclaredField("mDragCallback");
                mDragCallbackField.setAccessible(true);
                AppBarLayout.Behavior.DragCallback dragCallback = (AppBarLayout.Behavior.DragCallback) mDragCallbackField.get(behavior);
                return dragCallback;
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

Then just assertNotNull(getDragCallback(mAppBarLayout));

Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148
0

I ended up decomposing the creation of the behavior and for the unit test and verify that setDragCallBack was called with my custom behavior callback

protected AppBarLayout.Behavior createBehaviorWithCallBack(AppBarLayout.Behavior behavior) {
    behavior.setDragCallback(new MyCustomCallback());
    return behavior;
}

and for the unit test

assertNotNull(behavior);
verify(behavior).setDragCallback(any(MyCustomCallback.class));
SleepingLlama
  • 528
  • 1
  • 4
  • 8