我想编写一个测试来测试WebSocketHandlerDecorator,但遇到一些问题。
这是错误:
java.lang.IllegalArgumentException:委托不能为空
位于org.springframework.util.Assert.notNull(Assert.java:193) org.springframework.web.socket.handler.WebSocketHandlerDecorator。(WebSocketHandlerDecorator.java:42)
import org.springframework.util.Assert;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
public class MyWebSocketHandlerDecorator extends WebSocketHandlerDecorator {
public MySocketHandlerDecorator(WebSocketHandler delegate) {
super(delegate);
}
@Override
public void handleMessage(final WebSocketSession session, final WebSocketMessage<?> message) throws Exception {
final TextMessage MyMessage = (TextMessage) message;
super.handleMessage(session, MyMessage);
}
}
这是我的测试用例:
public class MyWebSocketHandlerDecpratorTest {
@Mock
private WebSocketSession session;
@Mock
WebSocketHandler delegate;
@Spy
private WebSocketHandlerDecorator webSocketHandlerDecorator = new WebSocketHandlerDecorator(delegate);
@InjectMocks
MyWebSocketHandlerDecorator myWebSocketHandlerDecorator;
private TextMessage message;
@Before
public void set_up(){
MockitoAnnotations.initMocks(this);
message = new TextMessage("Test Message".getBytes());
}
@Test
public void handleMessage()throws Exception{
myWebSocketHandlerDecorator.handleMessage(session, message);
verify(webSocketHandlerDecorator, times(1)).handleMessage(session, message);
}
}
有人可以帮助我更正我的测试并弄清楚它有什么问题吗?
public WebSocketHandlerDecorator(WebSocketHandler delegate) {
Assert.notNull(delegate, "Delegate must not be null");
this.delegate = delegate;
}
答案 0 :(得分:1)
您必须在@Spy
方法中设置@Before
,因为在创建类时,模拟尚未初始化:
public class MyWebSocketHandlerDecpratorTest {
@Mock
private WebSocketSession session;
@Mock
WebSocketHandler delegate;
private WebSocketHandlerDecorator webSocketHandlerDecorator;
@InjectMocks
MyWebSocketHandlerDecorator myWebSocketHandlerDecorator;
private TextMessage message;
@Before
public void set_up(){
MockitoAnnotations.initMocks(this);
webSocketHandlerDecorator = Mockito.spy(new WebSocketHandlerDecorator(delegate));
message = new TextMessage("Test Message".getBytes());
}
@Test
public void handleMessage()throws Exception{
myWebSocketHandlerDecorator.handleMessage(session, message);
verify(webSocketHandlerDecorator, times(1)).handleMessage(session, message);
}
}