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;
@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)
}
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With