我有一个看起来像这样的类:
class Service {
private final Logger lgr = LoggerFactory.getLogger(Service.class);
public void doService() {
lgr.info("Do Service");
}
}
public class Controller {
private final Logger lgr = LoggerFactory.getLogger(Controller.class);
@Autowired
private Service service;
protected void doSomething() {
//do something
lgr.info("LOG something"); // lgr line
// do something else
}
}
对应的测试类如下所示:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ControllerTest.class, LoggerFactory.class})
public class ControllerTest {
private Controller controller;
@Mock
private Service service;
@Before
public void init() {
controller = Mockito.mock(Controller.class, Mockito.CALLS_REAL_METHODS);
}
@Test
public void testDoSomething() {
controller.doSomething(); // calling doSomething method of Controller class
// some other statements
}
}
在这里,当调用到 doSomething() 方法时,在lgr line 行,lgr 对象为 null,因此我的单元测试因 NullPointerException 而失败。
有人可以帮我解决这个问题吗?