我听从了@Hoaz的建议。但是,我得到了nullpointer异常
@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)
}
}
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())
}
}
我还注意到DAO是null,所以我这样做了(只是为了提一下,我做了下面的步骤来尝试,我知道springUnit和Mockito或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)
}
如何使用Mockito模拟外部方法调用
如何使用Mockito在模拟对象上设置属性?
您还没有模仿ExternalDependencyObject
中getid
的行为,因此它返回null
,并在对该null
调用tostring()
时给出NPE。
您需要when(externaldependencyobject.getid()).then...