I’ve done a small test and in the second test I get an assertion error (0 instead of 1):
package tests;
import static org.junit.Assert.*;
import org.junit.Test;
import javax.swing.*;
public class MenuTest {
@Test
public void testElementsAddition() {
JMenuItem mItem1 = new JMenuItem();
JMenuItem mItem2 = new JMenuItem();
JMenu menu = new JMenu();
mItem1.add(mItem2);
assertEquals(1, mItem1.getComponentCount());
menu.add(mItem1);
assertEquals(1, menu.getComponentCount());
}
}
Any Ideas why this might happen?
This occurs because the menu item isn’t actually added to the
JMenuitself, but is added to a popup menu internally, there is actually nothing added to the menu.I think you will want to use
JMenu#getItemCount, which “Returns the number of items on the menu, including separators” or, preferably, JMenu#getMenuComponentCount