Creating a assertClass() method in JUnit

Posted by Mike on Stack Overflow See other posts from Stack Overflow or by Mike
Published on 2009-06-05T22:39:11Z Indexed on 2010/04/24 10:23 UTC
Read the original article Hit count: 155

Filed under:
|

Hi, I'm creating a test platform for a protocol project based on Apache MINA. In MINA when you receive packets the messageReceived() method gets an Object. Ideally I'd like to use a JUnit method assertClass(), however it doesn't exist. I'm playing around trying to work out what is the closest I can get. I'm trying to find something similar to instanceof.

Currently I have:

public void assertClass(String msg, Class expected, Object given) {
if(!expected.isInstance(given)) Assert.fail(msg);
}

To call this:

assertClass("Packet type is correct", SomePacket.class, receivedPacket);

This works without issue, however in experimenting and playing with this my interest was peaked by the instanceof operator.

if (receivedPacket instanceof SomePacket) { .. }

How is instanceof able to use SomePacket to reference the object at hand? It's not an instance of an object, its not a class, what is it?! Once establishing what type SomePacket is at that point is it possible to extend my assertClass() to not have to include the SomePacket.class argument, instead favouring SomePacket?

© Stack Overflow or respective owner

Related posts about java

Related posts about junit