我的java代码:
@Override
public void initConnection(WebSocketSession session) {
JSch jSch = new JSch();
SshConnectInfo sshConnectInfo = new SshConnectInfo();
sshConnectInfo.setJSch(jSch);
sshConnectInfo.setWebSocketSession(session);
String uuid = String.valueOf(session.getAttributes().get(ConstantPool.USER_UUID_KEY));
sshMap.put(uuid, sshConnectInfo);
}
我的测试类:
public class WebSshServiceImplTest {
private WebSshServiceImpl webSshService;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
this.webSshService = new WebSshServiceImpl(20);
}
@Mock
ConcurrentMap<String, Object> sshMap = new ConcurrentHashMap<>();
@Test
public void initConnectionSuccess() throws Exception{
WebSocketSession session = mock(WebSocketSession.class);
session.getAttributes().put(ConstantPool.USER_UUID_KEY,"asdfgh");
SshConnectInfo sshConnectInfo = new SshConnectInfo();
doReturn(sshConnectInfo).when(sshMap).put("asdfgh",sshConnectInfo);
webSshService.initConnection(session);
verify(sshMap,times(1)).put("asdfgh",sshConnectInfo);
}
当我运行此测试用例时,由于以下错误而失败
Wanted but not invoked:
sshMap.put(
"asdfgh",
SshConnectInfo(webSocketSession=null, jSch=null, channel=null)
);
-> at com.extremecloudiq.websshserver.service.WebSshServiceImplTest.initConnectionSuccess(WebSshServiceImplTest.java:48)
Actually, there were zero interactions with this mock.
有人能帮帮我吗?我试过自动装配serviceimpl,但它抛出空指针异常。不知道在代码中要修改什么。
1条答案
按热度按时间9fkzdhlc1#
我认为你根本没有注入mock,你有没有尝试过将注解
@InjectMocks
添加到WebSshServiceImpl
?请记住,
@InjectMocks
注解允许将@Mock
创建的不同模拟注入到底层对象中。