Mock NullPointerException

Remi0110 :

I try to do a Junit test for the method getPersonsFromAddress() in my service, i try to mock the object model, but when i execute the test a NullPointerException appears in the service when model.getPersons() is called.

Here is my service with the method getPersonsFromAddress():

@Service
public class ChildAlertService {

    @Autowired
    private Model model;

    @Autowired
    private Util util;

     public List<Person> getPersonsFromAdress (String address) {
         List<Person> listPersons = model.getPersons();
         List<Person> listPersonsFromAddress = new ArrayList<>();
         for (Person person : listPersons) {
             if(person.getAddress().contains(address)) {                    
                 listPersonsFromAddress.add(person);
                }
         }       
            return listPersonsFromAddress;
        }

Here is my test:

@ExtendWith(MockitoExtension.class)
public class ChildAlertServiceTest {

    private static ChildAlertService childAlertService;

    @Mock
    private Model model;

    @BeforeAll
    private static void setUp() {
        childAlertService = new ChildAlertService();
    }

    @Test
     public void testGetPersonsFromAdress () {
        List<Person> listPersons = new ArrayList<>();
        Person person1 = new Person();
        person1.setFirstName("John");
        person1.setFirstName("Boyd");
        person1.setAddress("1509 Culver St");


        listPersons.add(person1);

        Person person2 = new Person();
        person2.setFirstName("Roger");
        person2.setFirstName("Boyd");
        person1.setAddress("1509 Culver St");

        listPersons.add(person2);

        Person person3 = new Person();
        person3.setFirstName("Jonanathan");
        person3.setFirstName("Marrack");
        person3.setAddress("29 15th St");

        listPersons.add(person3);

        when(model.getPersons()).thenReturn(listPersons);

        String address = "1509 Culver St";
        List <Person> listPersonResult = childAlertService.getPersonsFromAdress(address);
        assertNotNull(listPersonResult);
        }

}

Thanks for your help.

Lesiak :

You never initialized model in ChildAlertService in your tests. Your Mock is never used.

In your prod code you rely on field injection.

See: What exactly is Field Injection and how to avoid it?

The cleanest approach is to use constructor injection in your service, and using that constructor in your tests (either manually, or via @InjectMocks)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=341225&siteId=1