简体   繁体   中英

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?

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM