有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Mockito在调用doCallRealMethod时抛出NullpointerException

我使用Mockito版本3.6.28进行Junit测试。调用对象上的实方法时,我收到Nullpointer异常。这是因为对目标对象的依赖关系没有正确注入。这是我使用的代码

    public class ClassA{

    @Autowired
    LoggingService loggingService;
    
    @Autowired
    ClassB classB;

    publc void doSomething(){
        loggingService.info("info log"); // This will works fine
        classB.doSomething();
    }
}

public class ClassB{

    @Autowired
    LoggingService loggingService;
    
    public void doSomething(){        
        loggingService.info("info log"); // Nullpointer on this line since loggingService is null
    }

}

@RunWith(MockitoJUnitRunner.Silent.class)
public class TestClass{

    @InjectMocks
    ClassA classA;
    
    @Mock
    ClassB classB;
    
    @Mock
    private LoggingService loggingService;
    
    @Test
    public void testMethod(){
        doCallRealMethod().when(classB).doSomething(); 
        classA.doSomething();
        
    }
}

共 (1) 个答案

  1. # 1 楼答案

    Mockito中的空指针异常通常是由缺少依赖项引起的,如您所说

    在您的例子中,ClassA被相应地注入,但是当涉及到ClassB时,它是一个Mock对象(即没有注入依赖项)

    因此,在使用ClassB时,必须注入MockClassB

    差不多

     @Test
        public void testMethod(){
    
            @InjectMocks
            ClassB classB_1;
    
            doCallRealMethod().when(classB_1).doSomething(); 
            classA.doSomething();
            
        }