gegossen werden habe ich eine Methode in der Klasse AppleProcessor
die Ich mag würde Test:Mockito Classcast - Ein Mock nicht
public void process(Fruit fruit) {
if(fruit.getType() == Fruit.APPLE) {
fruitBasket.add(((AppleFruit) fruit).getApple());
}
else {
// do something else
}
}
Beachten Sie, dass Obst ist eine Schnittstelle, mit der Methode getType()
die Geräte AppleFruit und hat auch eine getApple()
Methode.
Mein Test wie folgt aussieht:
@Mock
FruitBasket fruitBasket;
@Mock
Fruit fruit;
@Mock
AppleFruit apple;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testAnAppleIsProcessed() {
AppleProcessor appleProcessor = new AppleProcessoer();
when(fruit.getType()).thenReturn(Fruit.APPLE);
when(((AppleFruit) fruit).getApple()).thenReturn(apple);
appleProcessor.process(fruit);
verify(fruitBasket).add(isA(Apple.class));
}
Allerdings bekomme ich folgende Fehlermeldung:
java.lang.ClassCastException: package.fruit.Fruit$$EnhancerByMockitoWithCGLIB$$b8254f54 cannot be cast to package.fruit.AppleFruit
, die in dem Test von dieser Linie kommt
when(((AppleFruit) fruit).getApple()).thenReturn(apple);
Would irgendjemand k Wie kann ich das nun beheben, damit ich meinen Code testen kann?
Danke, der Test funktioniert jetzt. – user2844485