I'm trying to make a separate method for creating a list of mocks. E.g. we have a class Entity:
class Entity {
public List<SubEntity> subEntities;
}
But SubEntity is interface which has two implementations:
class SubEntityA implements SubEntity {
public SomeType someProp;
}
and
class SubEntityB implements SubEntity {
public SomeAnotherType someAnotherProp;
}
so I can have in subEnities property a mixed list of SubEntityA and SubEntityB objects.
In real case I have more then two types and I'd like to write a test where I need to generate a different amount of mocks of this classes and add it to the property subEntities. I can easily crate one mock using:
mock(SubEntityA.class)
but when I'm trying to do something like this:
private List<SubEntity> getMocks(Class<? extends SubEntity> classToMock, int amount) {
List<SubEntity> mocks = new ArrayList<>();
for (int i = 0; i < amount; i++) {
mocks.add(mock(classToMock));
}
return mocks;
}
I get into trouble using e.g. List<SubEntityA> list = getMocks(SubEntityA.class, 3), because SubEntityA.class or SubEntityB.class couldn't be casted to Class<? extends SubEntity>.
What I'm doing wrong? What shall I do to pass classes properly? I tried to find Mockito's methods but found only Mockito.anyListOf. As I understood It won't work in my case.
Thanks!
[UPD] The test looks like:
@Mock
private RepoSubA repoA;
@Mock
private RepoSubB repoB;
@Mock
private Repo repo;
@InjectMocks
private LogicBean testee;
@Test
public void test() {
//given
List<SubEntityA> listA = getMocks(SubEntityA.class, 3);
List<SubEntityB> listB = getMocks(SubEntityB.class, 3);
List<SubEntity> list = new ArraList<>();
list.addAll(listA);
list.addAll(listB);
Rule rule = someFixture();
when(repoA.getA(rule.getId())).thenReturn(listA);
when(repoB.getB(rule.getId())).thenReturn(listB);
//when
List<SubEntity> result = testee.someMagic(rule);
//then
assertThat(result, hasSize(list.size());
}
getMocks(SubEntityA.class, amount)will perfectly compile. Besides, you don't perform any cast in your code. Please share the full stracktrace.Error:(101, 84) java: incompatible types: java.util.List<model.SubEntity> cannot be converted to java.util.List<model.SubEntotyA>subEntities.SubEntityis an interface, why does it matter the actual type? Is there some instanceof/casting going on which is making testing harder?