This question already has answers here:
What is a NullPointerException, and how do I fix it?

(12个答案)


2天前关闭。





我同时开始使用Java和Mockito,因此我对我的testClass有很多疑问。我正在尝试测试:

public class ProjectManagerImpl implements ProjectManager {

    @ComponentImport
    private final ActiveObjects ao;

    @Inject
    public ProjectManagerImpl(ActiveObjects ao) {
        this.ao = checkNotNull(ao);
    }

public boolean methodToTest(ProjectParam projectParam) {
      ProjectType projectModel = getProjectById(id);

      if (projectParam.isActive() != projectModel.isActive() {
        return true;
      } else {
        return false;
      }

private List<ProjectModel> getProjectById(Long projectId) {
        return newArrayList(ao.find(Project.class, Query.select().where("PROJECT_ID = ?", projectId)));
    }


我正在尝试做这样的事情:

@RunWith(MockitoJUnitRunner.class)
public void class testClass() {
    @Mock
    private ActiveObjects ao;

    @InjectMocks
    private ProjectManagerImpl projectManager;

    @Test
    public void testMethodWhenParamAreTheSame {
        ProjectType projectModel = Mockito.mock(ProjectType.class);
        ProjectParam projectParam = Mockito.mock(ProjectParam.class);
        ProjectType[] listProjectType = new ProjectType[2];

        Mockito.when(projectType.isActive()).thenReturn(true);
        Mockito.when(projectParam.isActive()).thenReturn(true);

        Mockito.when(ao.find(Project.class, Query.select().where("PROJECT_ID = ?", projectId))).thenReturn(listProjectType);

        Mockito.when(projectManager.methodToTest(projectParam)).thenReturn(false);

        assertEquals(projectManager.methodToTest(projectParam), false);
    }



但是我收到此错误消息:

java.lang.NullPointerException
    at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:877)
    at com.google.common.collect.Lists.newArrayList(Lists.java:105)
    at com.X.ProjectManagerImpl.getProjectById(ProjectManagerImpl.java:73)


我究竟做错了什么 ?
“ getProjectById”方法是私有的。我是否仍然必须测试它,还是可以在尝试时模拟结果?

我将不胜感激!

最佳答案

私有getProjectById方法不是问题。
它使用了另一个服务ActiveObjects,您已正确模拟该服务并将其传递给被测对象。

您忘记为ao.find调用的getProjectById方法提供行为。
当Mockito看到与尚未定义的模拟的交互时,它将返回默认值(对象为null)。

注意:示例中的类型不匹配。你有:


List<ProjectModel> getProjectById(Long projectId)
ProjectType projectModel = getProjectById(id);


但是,这与讨论无关。

10-08 12:52