java – Mockito NullPointerException

我按照@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;

@John B解决方案解决了我的问题.但是,我想提一下对我不起作用的东西.这是我更新的单元测试

@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?

解决方法:

您还没有在externalDependencyObject中模拟getId的行为,因此它返回null并在该null上调用toString()时为您提供NPE.

你需要一个when(externalDependencyObject.getId()).然后……

上一篇:java – Mockito模拟SecurityManager抛出异常


下一篇:java – Mockito;使用list调用verify方法,忽略列表中元素的顺序