tags:

views:

107

answers:

3

I'm trying to create a MouseEvent with certain modifiers for UnitTesting. I'm using J2SE and the following code fails to pass:

public void testMouseEventProblem() {
  MouseEvent event = new MouseEvent(new JPanel(), 1, System.currentTimeMillis(), 
    InputEvent.CTRL_DOWN_MASK | InputEvent.ALT_DOWN_MASK, 1,1, 0, false);

  assertEquals(InputEvent.CTRL_DOWN_MASK | InputEvent.ALT_DOWN_MASK, event.getModifiers());
}

It's complaining saying "expected 640 but was 10"

What's going on?

+2  A: 

I don't think you should use assertEquals here.

You are checking that at least one of two specific bits are set in a value that could be anything, so you probably want to separate asserts.

Let me clarify this: You are getting a number that consists of a bunch of bits that are set (the modifiers), but you only care about two specific bits. With assertEquals, you are essentially saying that you want two specific bits sets, while the others are zero.

What you could do is assert that getModifiers() & ( MASK1 | MASK2 ) is greater than zero, since at least one of the two bits must be on for that to happen

That being said, something about those numbers looks funky, are you sure you are using the correct mask values?

Uri
But it would still be nice to know why getModifiers( ) returns a different quantity (I'm not a Java guy, just curious).
Ed Swangren
But you are correct, the OP should be ANDing to test specific bits.
Ed Swangren
To check for the bits being set on, you could do: assertEquals(InputEvent.CTRL_DOWN_MASK | InputEvent.ALT_DOWN_MASK, (InputEvent.CTRL_DOWN_MASK | InputEvent.ALT_DOWN_MASK)
Mark Bessey
+2  A: 

It gets internally converted to ALT_MASK and CTRL_MASK constants (8 + 2)

It happens in java.awt.event.InputEvent:405 in JDK 6

/**
 * Returns the modifier mask for this event.
 */
public int getModifiers() {
    return modifiers & (JDK_1_3_MODIFIERS | HIGH_MODIFIERS);
}

Try getModifiersEx():442:

public int getModifiersEx() {
    return modifiers & ~JDK_1_3_MODIFIERS;
}

As ALT_DOWN_MASK and friends are extended modifiers introduced after Java 1.3

Proof:

public class MouseEvt {
    public static void main(String[] args) {
        MouseEvent event = new MouseEvent(new JPanel(), 1, System
                .currentTimeMillis(), InputEvent.CTRL_DOWN_MASK
                | InputEvent.ALT_DOWN_MASK, 1, 1, 0, false);

        System.out.printf("%d - %d%n", InputEvent.CTRL_DOWN_MASK 
            | InputEvent.ALT_DOWN_MASK,
            event.getModifiersEx());
    }
}

Returns 640 - 640

kd304
A: 

To expand on Uri's answer, you probably want to say something like

assert(InputEvent.CTRL_DOWN_MAsK & event.getModifiers() != 0);
assert(InputEvent.ALT_DOWN_MAsK & event.getModifiers() != 0);

This will check that both modifiers are pressed, without regard to the rest of the string, which it seems is something else.

Mike Cooper