Mockito mock throwing a NPE even when the mocks are activated

I am trying to mock a call baseUtils.getIdentificationType(id.getType().getName()) but the instance baseUtils is always null and hence throws NPE when that method is called. I have mocked baseUtils and using Mockito.initMocks(this)

Base class

class Base {

    protected BaseUtils baseUtils;

protected void populateIdentification(Person person, final List<Id> issuedIds) {
        List<Identification> identificationList = new ArrayList<>();
        if (issuedIds != null && issuedIds.size() > 0) {
            for (Id id : issuedIds) {
                Identification identification = new Identification();

                // BELOW CALL TO MOCK BUT baseUtils returns null hence NPE in the test 
                String idType = baseUtils.getIdentificationType(id.getType().getName()); 

                if (idType != null) {
                } else {
                if (issuedId.getCountryCode() != null) {
                    CountryCodeEnum codeEnum = CountryCodeEnum.valueOf(govtIssuedId.getCountryCode());

class Child extends Base {



public class BaseUtils {

    private Map<String, String> idToIdType;

    public BaseUtils() {
        idToIdType = new HashMap<>();
        idToIdType.put("ID1", "A");
        idToIdType.put("ID2", "B");
        idToIdType.put("ID3", "C");

    public String getIdentificationType(String documentType) {
        if (idToIdType.containsKey(documentType)) {
            return idToIdType.get(documentType);
        return null;


public class ChildTest {

    private BaseUtils baseUtils;

    Child child = new Child();

    public void init() {


    public void populateIdentificationTest() {
        Child child = new Child();
        Person person = new Person();
        UserData userData = createUserData();
        List<IssuedId> issuedIds = userData.getIssuedIds();

        doReturn("ABC").when(baseUtils).getIdentificationType(anyString());  //MOCKED CALL
        child.populateIdentification(person, issuedIds);


I have reviewed other questions and this is how its done there so not sure what am I not following. Some help will be really appreciated 🙂


I think the problem is here: You use @InjectMocks Child child = new Child(); to inject your BaseUtils Mock. But in your @Test you create a new instance of Child. Do not do that. Use your Child instance you created in @InjectMocks Child child = new Child();.

Leave a Reply

Your email address will not be published. Required fields are marked *