Creating the assertClass () method in JUnit

I am creating a test platform for a protocol project based on Apache MINA. In MINA, when you receive packets, the method messageReceived()receives an object. Ideally, I would like to use the JUnit method assertClass(), however it does not exist. I play around trying to figure out what is the closest I can get. I'm trying to find something similar to instanceof.

I currently have:

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

To trigger this:

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

This works without problems, however, experimenting and playing with it, my interest was reached by the peak of the operator instanceof.

if (receivedPacket instanceof SomePacket) { .. }

SomePacket ? , , ?! , SomePacket , assertClass(), SomePacket.class, SomePacket?

+3
6
0

Hamcrest, JUnit. , , - :

import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.instanceOf;

assertThat(receivedPacket, instanceOf(SomePacket.class));

, , .

+24

assertEquals?

assertEquals(SomePacket.class, given.getClass());
+2

SomePacket - , :

 SomePacket something = null;

, . - , .

0

FYI,

if(given == null || given.getClass() != expected)

, given expected, .
assertClass assertInstance assertInstanceOf.

:
, . "FYI", ;)

, , .

public class Base {}
public interface Ifc {}

public class A{} extends Base implements Ifc
public class B{} extends Base

,

A a=new A();
B b=new B();

assertClass(A.class, a);
assertClass(Base.class, a); // fails, a.getClass() != Base.class
assertClass(Ifc.class, a); // fails, a.getClass() != Ifc.class
assertClass(B.class, b);
assertClass(Base.class, b); // fails, b.getClass() != Base.class
assertClass(Ifc.class, b); // fails, b.getClass() != Ifc.class

assertInstance(A.class, a);
assertInstance(Base.class, a); // works
assertInstance(Ifc.class, a); // works
assertInstance(B.class, b);
assertInstance(Base.class, b); // works
assertInstance(Ifc.class, b); // fails, B does not implement Ifc

, .
, . , , .

0
assertThat(expected).isInstanceOf(given.class);

FEST Assertions 2.0 - Java- , : https://github.com/alexruiz/fest-assert-2.x/wiki

0

Source: https://habr.com/ru/post/1709889/


All Articles