externalDependencyObject

externalDependencyObject

本文介绍了Mockito NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按照@hoaz的建议。但是,我得到nullpointer异常

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())
    }
}

我也注意到DAO是空的所以我做了这个(只是提到,我做了下面的步骤尝试,我知道springUnit和Mockito或xyz之间的区别):

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解决方案解决了我的问题。不过我想提一下对我不起作用的东西。这是我更新的单元测试


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

推荐答案

您还没有嘲笑 getId externalDependencyObject 中,因此它返回 null 并给你当 toString() null 上调用NPE时。

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())。然后......

这篇关于Mockito NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 01:23