我知道我不應該測試這樣的無效方法,但我只是用一個簡單的例子來測試Mockito.doNothing()。Mockito.doNothing()一直返回空指針異常
我的服務類:
@Service
public class Service{
@Autowired
private Consumer<String, String> kafkaConsumer;
public void clearSubscribtions(){
kafkaConsumer.unsubscribe();
}
}
我的測試類:
@MockBean
private Consumer<String, String> kafkaConsumer;
@Test
public void testClearSubscriptions() {
Service service = new Service();
Mockito.doNothing().when(kafkaConsumer).unsubscribe();
service.clearSubscriptions();
}
測試保持與空指針異常失敗。當我調試它時,它進入服務類的clearSubscription方法,並且在kafkaConsumer.unsubscribe()的行上,kafkaConsumer爲null。但我嘲笑消費者,爲什麼它拋出空指針異常,我應該跳過這種方法,對吧?
編輯: 所有類的聲明:
@Autowired
private Consumer<String, String> kafkaConsumer;
@Autowired
private Service2 service2;
private final Object lock = new Object();
private static Logger logger = LoggerFactory.getLogger(Service.class);
private HashMap<String, String> subscribedTopics = new HashMap<>();
想通了什麼是錯的,我需要自動線
因爲我認爲該領域嘲笑從不嘲笑加樣。你似乎混合了Spring和Mockito。你能展示全班的聲明嗎?我認爲問題在那裏。 – davidxxx