3

I have a problem. I want to write a test for code that relies on execution of the PopupWindow.OnDismissListener.onDismiss() method. However, it never seems to be called. Am I doing something wrong?

Sample code:

View content = new View(Robolectric.application);
PopupWindow popup = new PopupWindow(content, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            Assert.fail();
        }
});
View anchor = new View(Robolectric.application);
popup.showAsDropDown(anchor);
popup.dismiss();

The above test never fails! I have tried adding a small sleep after, in case there were some timing issues. I have looked at the generated code for the PopupWindow.class, but couldn't find anything there either.

Thanks!

2 Answers2

0

I generally prefer using dialog boxes instead. To build an AlertDialog, use something like below from the Developers page:

/ 1. Instantiate an AlertDialog.Builder with its constructor 
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

// 2. Chain together various setter methods to set the dialog characteristics 
builder.setMessage(R.string.dialog_message)
       .setTitle(R.string.dialog_title);

// 3. Get the AlertDialog from create() 
AlertDialog dialog = builder.create();
Cybergenie
  • 79
  • 6
  • Thank you for the tip! I can't change the type though, and I need to know if this is a bug, if there is a workaround or if I'm doing anything wrong... – Elisabet Svensson Jan 30 '15 at 11:01
0

The reason why the listener isn't called is because the ShadowPopupWindow from Robolectric overrides the default implementation and simply doesn't call it.

Code from source:

  public void dismiss() {
    if (context != null) {
      getWindowManager().removeView(containerView);
    }
    showing = false;
  }

Depending on what it is you need to test, there may be a valid workaround (your sample code above pretty much just tests the internals of PopupWindow, which I am guessing is not what you are actually looking to achieve). You could also make your own custom shadow, extending this one, where you choose to do a different behaviour.

Alex Florescu
  • 5,096
  • 1
  • 28
  • 49