|
| 1 | +package com.baeldung.casting; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | +import static org.junit.Assert.*; |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | +public class CastingTest { |
| 9 | + |
| 10 | + @Test |
| 11 | + public void whenPrimitiveConverted_thenValueChanged() { |
| 12 | + double myDouble = 1.1; |
| 13 | + int myInt = (int) myDouble; |
| 14 | + assertNotEquals(myDouble, myInt); |
| 15 | + } |
| 16 | + |
| 17 | + @Test |
| 18 | + public void whenUpcast_thenInstanceUnchanged() { |
| 19 | + Cat cat = new Cat(); |
| 20 | + Animal animal = cat; |
| 21 | + animal = (Animal) cat; |
| 22 | + assertTrue(animal instanceof Cat); |
| 23 | + } |
| 24 | + |
| 25 | + @Test |
| 26 | + public void whenUpcastToObject_thenInstanceUnchanged() { |
| 27 | + Object object = new Animal(); |
| 28 | + assertTrue(object instanceof Animal); |
| 29 | + } |
| 30 | + |
| 31 | + @Test |
| 32 | + public void whenUpcastToInterface_thenInstanceUnchanged() { |
| 33 | + Mew mew = new Cat(); |
| 34 | + assertTrue(mew instanceof Cat); |
| 35 | + } |
| 36 | + |
| 37 | + @Test |
| 38 | + public void whenUpcastToAnimal_thenOverridenMethodsCalled() { |
| 39 | + List<Animal> animals = new ArrayList<>(); |
| 40 | + animals.add(new Cat()); |
| 41 | + animals.add(new Dog()); |
| 42 | + new AnimalFeeder().feed(animals); |
| 43 | + } |
| 44 | + |
| 45 | + @Test |
| 46 | + public void whenDowncastToCat_thenMeowIsCalled() { |
| 47 | + Animal animal = new Cat(); |
| 48 | + ((Cat) animal).meow(); |
| 49 | + } |
| 50 | + |
| 51 | + @Test(expected = ClassCastException.class) |
| 52 | + public void whenDownCastWithoutCheck_thenExceptionThrown() { |
| 53 | + List<Animal> animals = new ArrayList<>(); |
| 54 | + animals.add(new Cat()); |
| 55 | + animals.add(new Dog()); |
| 56 | + new AnimalFeeder().uncheckedFeed(animals); |
| 57 | + } |
| 58 | +} |
0 commit comments