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 :
someDao.findMe(someObject.getId.toString())
execute it does NOT trigger my MockDao return statement, but instead tries to evaluatesomeObject.getId.toString()
. When I did println in the test forsomeDao.findMe
it does return the collection. I also checked the debugging,someDao
is already set property into generalConfigService. So not sure why it's evaluating and not just returning my collection – Anuj