Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito NullPointerException

I followed what @hoaz suggested. However, I am getting nullpointer exception

@RunWith(MockitoJUnitRunner.class)
public class GeneralConfigServiceImplTest  {

@InjectMocks private GeneralConfigService generalConfigService;
@Mock private SomeDao someDao;
@Mock private ExternalDependencyClass externalDependencyObject 

@Test
public void testAddGeneralConfigCallDAOSuccess() {
    when(someDao.findMe(any(String.Class))).thenReturn(new ArrayList<String>(Arrays.asList("1234")));

    //println works here, I am able to get collection from my mocked DAO

    // Calling the actual service function
    generalConfigService.process(externalDependencyObject)
    }
}

In my Code it's like this:

import com.xyz.ExternalDependencyClass;

public class  GeneralConfigService{

private SomeDao someDao;

public void process(ExternalDependencyClass externalDependencyObject){

// function using Mockito 
Collection<String> result = someDao.findMe(externalDependencyObject.getId.toString())
    }
}

I also notice that DAO was null so I did this(Just to mention, I did the below step to try, I know the difference between springUnit and Mockito or xyz):

@Autowired
private SomeDao someDao;


@John B solution solved my problem. However I would like to mention what did not work for me. This is my updated unit test
@Test
public void testAddGeneralConfigCallDAOSuccess() {
    /*
    This does not work
    externalDependencyObject.setId(new ExternalKey("pk_1"));
    // verify statement works and I thought that the class in test when call the getId 
    // it will be able to get the ExternalKey object
    //verify(externalDependencyObject.setId(new ExternalKey("pk_1")));
    */

    // This works
    when(externalDependencyObject.getId()).thenReturn(new ExternalKey("pk_1"));
    when(someDao.findMe(any(String.Class))).thenReturn(new ArrayList<String>(Arrays.asList("1234")));

    ....
    // Calling the actual service function
    generalConfigService.process(externalDependencyObject)
    }


Referenced this question in :

How do I mock external method call with Mockito

How do I set a property on a mocked object using Mockito?

like image 906
Anuj Avatar asked Jun 06 '14 00:06

Anuj


1 Answers

You haven't mocked the behavior of getId in externalDependencyObject therefore it is returning null and giving you the NPE when toString() is called on that null.

You need a when(externalDependencyObject.getId()).then...

like image 55
John B Avatar answered Oct 27 '22 03:10

John B