无法模拟 TextMessage

unable to mock TextMessage

有人可以帮助我如何模拟这一行,我试过并得到空指针异常

mockTextMessage = mock(TextMessage.class);
when(mockTextMessage.getText()).thenReturn(any(String.class));


public void onMessage(Message message) {
    String text = ((TextMessage)message).getText();
}

您应该在 thenReturn() 方法中传递实际对象。

见下面thenReturn(T value)

的定义

Sets a return value to be returned when the method is called.
"When the x method is called then return y".

例子

when(mock.x()).thenReturn(y); 
when(mock.someMethod()).thenReturn(10);

在您的情况下,传递您希望在 mockTextMessage 上调用 getText() 方法时返回的实际字符串值。

when(mockTextMessage.getText()).thenReturn("expected value");