junit 实际上,与这个模拟没有任何交互,通缉但未被援引

57hvy0tb  于 2023-05-29  发布在  其他
关注(0)|答案(1)|浏览(161)

我的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,但它抛出空指针异常。不知道在代码中要修改什么。

9fkzdhlc

9fkzdhlc1#

我认为你根本没有注入mock,你有没有尝试过将注解@InjectMocks添加到WebSshServiceImpl
请记住,@InjectMocks注解允许将@Mock创建的不同模拟注入到底层对象中。

@InjectMocks
private WebSshServiceImpl webSshService;

相关问题