Open alisevych opened 11 months ago
Investigated with @tepa46 and @Vassiliy-Kudryashov - looks like a very strange case.
There is no obvious reasons why Spring cannot inject this Spy into the instance under test. It can be manually fixed if we replace ArrayList
with ArrayList<Pet>
, but we cannot generate such code due to generics support limitations in UnitTestBot.
Tomorrow I'm going to ask other collegues if they see the reasons of autowiring problems here. If we clarify it, it may be possible to use some fallback as we do when there are several lists of one type in project.
It seems to be a bug in Mockito.
Consider the following test
@Test
@DisplayName("getPet: compId.equals(id) : True -> return pet")
public void testGetPet_CompIdEquals() throws Exception {
Pet petMock = mock(Pet.class);
(when(petMock.isNew())).thenReturn(false);
(when(petMock.getId())).thenReturn(-255);
pets.add(petMock);
pets.add(null);
pets.add(null);
Integer id = -255;
Pet actual = owner.getPet(id);
assertNull(actual.getBirthDate());
assertNull(actual.getType());
Set actualVisits = ((Set) getFieldValue(actual, "org.springframework.samples.petclinic.owner.Pet", "visits"));
assertNull(actualVisits);
assertNull(actual.getName());
assertNull(actual.getId());
}
This version does not work
@InjectMocks
private Owner owner;
@Spy
private ArrayList pets;
This version works
@InjectMocks
private Owner owner;
private ArrayList pets = Mockito.spy(new ArrayList());
However, in accordance with @Spy
documentation, it must be the same.
Seems to be a generics support problems in @InjectMocks
. There are some other known issues about it, like https://github.com/mockito/mockito/issues/1066.
@EgorkaKulikov Can we generate code like it is in your second example? With explicit spy creation?
@Spy annotation was constructed as a smart syntax and guidelines recommend it. After that, here we know one seldom bug, I have no idea how many potential problems are hidden in it. It can be investigated, but it will take time.
Description
linkedListSpy is created and configured, but not injected into Entity under test
To Reproduce
spring-petclinic
Unit tests
forOwner
withPetClinicApplication
configurationExpected behavior
No NPE should be thrown from get-methods of the entity before assertions.
Actual behavior
There are several tests throwing NPE when getting fields of actual Pet.
Screenshots, logs
Environment
IntelliJ IDEA version - Community 2023.2 Project - Maven JDK - 17
Additional context
When debugging, linkedListSpy is returning expected values. There is pet returning isNew()=false and getId()=0. But owner.getPets() returns empty list.