Add new section on instanceof

This commit is contained in:
515882294 2021-09-14 19:41:34 +08:00
parent 6a638120dc
commit 28d708a2fa
1 changed files with 62 additions and 12 deletions

View File

@ -8,7 +8,30 @@ import org.junit.Test;
public class IsInstanceIsAssignableFromUnitTest {
@Test
public void whenUsingIsInstanceProperly_desiredResultsHappen() {
public void whenUsingInstanceOfProperly_thenDesiredResultsHappen() {
Shape shape = new Triangle();
Triangle triangle = new Triangle();
IsoscelesTriangle isoscelesTriangle = new IsoscelesTriangle();
Shape nonspecificShape = null;
assertTrue(shape instanceof Shape);
assertTrue(triangle instanceof Shape);
assertTrue(isoscelesTriangle instanceof Shape);
assertFalse(nonspecificShape instanceof Shape);
assertTrue(shape instanceof Triangle);
assertTrue(triangle instanceof Triangle);
assertTrue(isoscelesTriangle instanceof Triangle);
assertFalse(nonspecificShape instanceof Triangle);
assertFalse(shape instanceof IsoscelesTriangle);
assertFalse(triangle instanceof IsoscelesTriangle);
assertTrue(isoscelesTriangle instanceof IsoscelesTriangle);
assertFalse(nonspecificShape instanceof IsoscelesTriangle);
}
@Test
public void whenUsingIsInstanceProperly_thenDesiredResultsHappen() {
Shape shape = new Triangle();
Triangle triangle = new Triangle();
IsoscelesTriangle isoscelesTriangle = new IsoscelesTriangle();
@ -33,7 +56,7 @@ public class IsInstanceIsAssignableFromUnitTest {
}
@Test
public void whenUsingIsAssignableFromProperly_desiredResultsHappen() {
public void whenUsingIsAssignableFromProperly_thenDesiredResultsHappen() {
Shape shape = new Triangle();
Triangle triangle = new Triangle();
IsoscelesTriangle isoscelesTriangle = new IsoscelesTriangle();
@ -64,4 +87,31 @@ public class IsInstanceIsAssignableFromUnitTest {
assertTrue(isoscelesTriangle2.getClass().isAssignableFrom(isoscelesTriangle2.getClass()));
}
@Test(expected = NullPointerException.class)
public void whenUsingNull_thenDesiredResultsHappen() {
assertFalse(null instanceof Shape);
assertFalse(Shape.class.isInstance(null));
assertFalse(Shape.class.isAssignableFrom(null)); // NullPointerException
}
@Test
public void whenUsingPrimitiveType_thenDesiredResultsHappen() {
//assertFalse(10 instanceof int); // illegal
assertFalse(int.class.isInstance(10));
assertTrue(Integer.class.isInstance(10));
assertTrue(int.class.isAssignableFrom(int.class));
assertFalse(float.class.isAssignableFrom(int.class));
}
@Test
public void whenUsingClassInstanceVariable_thenDesiredResultsHappen() {
Shape shape = new Triangle();
Triangle triangle = new Triangle();
Class<?> clazz = shape.getClass();
//assertFalse(triangle instanceof clazz); // illegal
assertTrue(clazz.isInstance(triangle));
assertTrue(clazz.isAssignableFrom(triangle.getClass()));
}
}