[英]Mockito NullPointerException
I followed what @hoaz suggested. 我按照@hoaz的建议。 However, I am getting nullpointer exception
但是,我得到了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)
}
}
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): 我也注意到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) }
How do I mock external method call with Mockito 如何使用Mockito模拟外部方法调用
How do I set a property on a mocked object using Mockito? 如何使用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
. 您还没有在
externalDependencyObject
中getId
的行为,因此它返回null
并在该null
上调用toString()
时为您提供NPE。
You need a when(externalDependencyObject.getId()).then...
你需要一个
when(externalDependencyObject.getId()).then...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.