10

I have an android customView which I want to test.

Few of the tests simulate a scroll of N dps when N is a subView height.

I run the tests with robolectric, but I always get in runtime that subView.getHeight() == 0

That's becuause the subView's height is defined as wrap_content and I guess robolectric doesn't inflate all the views to get this accurate info.

For example the subView.getWidth > 0 as its defined as match parent.

Here is my test @before method:

@Before
  public void setUp() {

    myView.getHeaderView().getViewTreeObserver().addOnGlobalLayoutListener(
        new OnGlobalLayoutListener() {
          @Override
          public void onGlobalLayout() {
            myHeight =
                myView.getHeaderView().getHeight();
          }
        });

    activityScenarioRule
        .getScenario()
        .onActivity(activity -> activity.setContentView(myView));
    activityScenarioRule.getScenario().moveToState(State.RESUMED);
  }

How can I still get the wrap content height at test runtime?

The code does call onGlobalLayout but returns height==0

Elad Benda
  • 35,076
  • 87
  • 265
  • 471
  • Try to call measure() and layout() on your SubView, &/or set a ViewTreeObserver.OnGlobalLayoutListener on the SubView and from there you get the View Dimensions – User One May 06 '19 at 17:59
  • doesn't it called automatically? you mean to call from prod code? – Elad Benda May 06 '19 at 18:01
  • You may get the height too fast for the subview, a reason for why it return 0, if on the prod code you are getting the View dimensions before the View is ready, it's better to get it with a ViewTreeObserver.OnGlobalLayoutListener so you are sure the view has called it's methods, you can test it on the Test code for the moment and see if it's work – User One May 06 '19 at 18:04
  • but why do i get the view's height then? – Elad Benda May 06 '19 at 20:41
  • registering to `ViewTreeObserver.OnGlobalLayoutListener` in the test `@before` didn't solve it – Elad Benda May 06 '19 at 20:42
  • @Benda you get the first View height by "luck" and too fast to get the second, getting the height synchronously when the View are about to be drawn may result in dimensions returning 0(getHeight() before the view is ready), with the ViewTreeObserver you are sure you can get the View infos, if it did not worked then your problem may lie elsewhere too, try as stated in my first comment to call measure() and layout() see if it's work – User One May 07 '19 at 14:53

1 Answers1

1

Use @TextLayoutMode(REALISTIC) annotation above your test method.

Vivek Vashistha
  • 832
  • 9
  • 17