Tôi có một phương pháp trong lớp AppleProcessor
mà tôi muốn thử nghiệm:Mockito ClassCastException - Một mô hình không thể được đúc
public void process(Fruit fruit) {
if(fruit.getType() == Fruit.APPLE) {
fruitBasket.add(((AppleFruit) fruit).getApple());
}
else {
// do something else
}
}
Lưu ý rằng trái cây là một giao diện với phương pháp getType()
mà AppleFruit thực hiện và cũng có một getApple()
.
thử nghiệm của tôi trông giống như:
@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));
}
Tuy nhiên tôi nhận được lỗi sau:
java.lang.ClassCastException: package.fruit.Fruit$$EnhancerByMockitoWithCGLIB$$b8254f54 cannot be cast to package.fruit.AppleFruit
mà xuất phát từ dòng này trong các thử nghiệm
when(((AppleFruit) fruit).getApple()).thenReturn(apple);
Would bất cứ ai k bây giờ làm thế nào để giải quyết điều này vì vậy tôi có thể kiểm tra mã của tôi?
Cảm ơn, thử nghiệm hoạt động ngay bây giờ. – user2844485