【发布时间】:2021-10-03 16:56:19
【问题描述】:
我正在使用 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();
}
}
【问题讨论】:
标签: java spring junit mockito springmockito